dynamic allocating array of arrays in C

后端 未结 7 899
南笙
南笙 2020-11-30 04:08

I don\'t truly understand some basic things in C like dynamically allocating array of arrays. I know you can do:

int **m;

in order to decla

7条回答
  •  一生所求
    2020-11-30 05:05

    The m[line][column] = 12 syntax is ok (provided line and column are in range).

    However, you didn't write the code you use to allocate it, so it's hard to get whether it is wrong or right. It should be something along the lines of

    m = (int**)malloc(nlines * sizeof(int*));
    
    for(i = 0; i < nlines; i++)
      m[i] = (int*)malloc(ncolumns * sizeof(int));
    

    Some side-notes:

    • This way, you can allocate each line with a different length (eg. a triangular array)
    • You can realloc() or free() an individual line later while using the array
    • You must free() every line, when you free() the entire array

提交回复
热议问题