initialize a multidimensional C array of variable size to zero

后端 未结 5 1996
小蘑菇
小蘑菇 2021-02-08 07:03

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};
<
相关标签:
5条回答
  • 2021-02-08 07:32

    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().

    0 讨论(0)
  • 2021-02-08 07:33

    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.

    0 讨论(0)
  • 2021-02-08 07:33

    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);
    
    0 讨论(0)
  • 2021-02-08 07:40

    If you get a pointer to your data structure, you could try memset.

    0 讨论(0)
  • 2021-02-08 07:45

    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.

    0 讨论(0)
提交回复
热议问题