0

I am trying to initialise a 2d-array to 0 in C of size m x n which are inputs in my function. Here is an example (not interested in the output hence void type):

void createArray(int m, int n)
{
    int array[m][n]={0};
}

I get the error: "Variable-sized object may not be initialized". I had no luck when I used "const int" instead of "int" also.

This works fine if I don't try to assign 0 to the array:

void createArray(int m, int n)
{
    int array[m][n];
}

Is there a way around this? It seems inefficient to have to loop over the array setting all values to 0, but maybe this is how C initialises it anyway?

Sam
  • 55
  • 5

1 Answers1

1

It seems inefficient to have to loop over the array setting all values to 0

It won't affect the performance. The initialization loop is transformed into a call to memset zero ( for gcc -O3 compiler flag )

memset(array, 0, sizeof(array));

reference - https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

Samir Kape
  • 1,733
  • 1
  • 16
  • 19
  • 1
    I do not get the first line of this. Is it the same as the "you can try"? Also, please be more assertive, i.e. away "try" answers please. – Yunnosch Sep 16 '20 at 10:06
  • 1
    A loop may be more, less or equally efficient as `memset`. `memset` might have to deal with precautions in case of misalignment, which a plain for loop won't need to do. – Lundin Sep 16 '20 at 10:21