I want to initialize a two-dimensional array of variable size to zero. I know it can be done for a fixed-sized array:
int myarray[10][10] = {0};
<
Online C99 Standard (n1256 draft), Section 6.7.8, para 3:
The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.
Emphasis mine.
As everyone else has said, your best bet is to use memset()
.
You cannot initialize it with an initializer, but you can memset()
the array to 0.
#include <string.h>
int main(void) {
int a = 13, b = 42;
int m[a][b];
memset(m, 0, sizeof m);
return 0;
}
Note: this is C99
. In C89
the declaration of m ( int m[a][b];
) is an error.
You can't create a static array using non-constant variables. Try using dynamic allocation:
int i = 10;
int j = 10;
size_t nbytes = i*j*sizeof(int);
int* myarray = (int*) malloc(nbytes);
memset(myarray,0,nbytes);
If you get a pointer to your data structure, you could try memset.
Variable size two dimensional arrays are not supported in C. One dimension (i can't remember if it is first or second) has to be fixed. I recommend looping over it once it is defined.