Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize a multidimensional C array of variable size to zero

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

like image 714
Ben2209 Avatar asked Sep 15 '10 14:09

Ben2209


People also ask

Can you initialize an array with a variable size in C?

The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.

Should you initialize an array variable to 0?

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.

How do you create multidimensional arrays in C?

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.


1 Answers

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.

like image 56
pmg Avatar answered Nov 01 '22 05:11

pmg