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
The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.
If you are going to use values from the array right after it is created, you want those values to have something. In the absence of further information, 0 is a good starting value. If you are going to use the array only to store values (at the beginning) and you don't really care what's in it, don't initialize.
The basic form of declaring a two-dimensional array of size x, y: Syntax: data_type array_name[x][y]; Here, data_type is the type of data to be stored.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With