Allocate a 2d array in C with one dimension fixed

前端 未结 3 1767
野趣味
野趣味 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:29

    You have to allocate a new array for each element (each element is a pointer to an array) on the first dimension. You can use a loop for that:

    for(i = 0; i < NCOLS; i++)
       arr[i] = (double *)malloc(sizeof(double)*nrows);
    

    Do the same to free.

提交回复
热议问题