Allocate a 2d array in C with one dimension fixed

前端 未结 3 1741
野趣味
野趣味 2021-01-14 15:31

I want to dynamically allocate 1 dimension of a 2D array (the other dimension is given). Does this work:

int NCOLS = 20;

// nrows = user input...

double *a         


        
3条回答
  •  余生分开走
    2021-01-14 16:07

    Not quite -- what you've declared is an array of pointers. You want a pointer to an array, which would be declared like this:

    double (*arr)[NCOLS];
    

    Then, you'd allocate it like so:

    arr = malloc(nrows * sizeof(double[NCOLS]));
    

    It can then be treated as a normal nrows by NCOLS 2D array. To free it, just pass it to free like any other pointer.

    In C, there's no need to cast the return value of malloc, since there's an implicit cast from void* to any pointer type (this is not true in C++). In fact, doing so can mask errors, such as failing to #include , due to the existence of implicit declarations, so it's discouraged.

    The data type double[20] is "array 20 of double, and the type double (*)[20] is "pointer to array 20 of double". The cdecl(1) program is very helpful in being able to decipher complex C declarations (example).

提交回复
热议问题