I want to initialize a 2D array with -1 as all the value. I used memset()
for this.
#include
using namespace std;
int dp[100]
There is no way (at least I do not know any) to initialize all the elements of an array with a specific value other than 0
.
You can somehow work around in that you call memset
in the course of initializing another variable at file scope:
int dp[100][100];
auto x = memset(dp, -1, sizeof(dp));
int main() {
cout<
But note: the order of global variable initialization is not guaranteed; the only thing you can rely on is that the memset
will have been executed before function main
is entered. But then you could do it as first line in main
as well.
Note further that you need good luck when you want to initialize an array elements of type int
, as a single int comprises more than one byte; memset
fills the elements at byte level, not at element type level. For example, memset(dp, -2, sizeof(dp))
will not lead to an array filled with -2
then; and even -1
requires the architecture to be two's complement to work.