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 *arr[NCOLS];
arr = (double *)malloc(sizeof(double)*nrows);
and to free it:
free(arr)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Not quite — what you’ve declared is an array of pointers. You want a pointer to an array, which would be declared like this:
Then, you’d allocate it like so:
It can then be treated as a normal
nrowsbyNCOLS2D array. To free it, just pass it tofreelike any other pointer.In C, there’s no need to cast the return value of
malloc, since there’s an implicit cast fromvoid*to any pointer type (this is not true in C++). In fact, doing so can mask errors, such as failing to#include <stdlib.h>, due to the existence of implicit declarations, so it’s discouraged.The data type
double[20]is “array 20 ofdouble, and the typedouble (*)[20]is “pointer to array 20 ofdouble“. Thecdecl(1)program is very helpful in being able to decipher complex C declarations (example).