问题
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};
but it is not working if I do this:
int i = 10;
int j = 10;
int myarray[i][j] = {0};
Is there a one-line way of doing this or do I have to loop over each member of the array?
Thanks
回答1:
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.
回答2:
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()
.
回答3:
If you get a pointer to your data structure, you could try memset.
回答4:
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);
回答5:
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.
来源:https://stackoverflow.com/questions/3718716/initialize-a-multidimensional-c-array-of-variable-size-to-zero