Initializing entire 2D array with one value Initializing entire 2D array with one value c c

Initializing entire 2D array with one value


You get this behavior, because int array [ROW][COLUMN] = {1}; does not mean "set all items to one". Let me try to explain how this works step by step.

The explicit, overly clear way of initializing your array would be like this:

#define ROW 2#define COLUMN 2int array [ROW][COLUMN] ={  {0, 0},  {0, 0}};

However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:

int array [ROW][COLUMN] ={  {1, 2}};

This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.

So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.

Next, there is a rule in C allowing lax brace style. The first example could as well be written as

int array [ROW][COLUMN] = {0, 0, 0, 0};

although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write

int array [ROW][COLUMN] = {0};

which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."

therefore, if you attempt

int array [ROW][COLUMN] = {1};

it means "initialize the very first column in the first row to 1 and set all other items to zero".


If you want to initialize the array to -1 then you can use the following,

memset(array, -1, sizeof(array[0][0]) * row * count)

But this will work 0 and -1 only


int array[ROW][COLUMN]={1};

This initialises only the first element to 1. Everything else gets a 0.

In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.

The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.

With a char array you could use memset to set every byte, but this will not generally work with an int array (though it's fine for 0).

A general for loop will do this quickly:

for (int i = 0; i < ROW; i++)  for (int j = 0; j < COLUMN; j++)    array[i][j] = 1;

Or possibly quicker (depending on the compiler)

for (int i = 0; i < ROW*COLUMN; i++)  *((int*)a + i) = 1;