2d array
how to dynamically allocate a 2d arry using malloc in c language
the user will input a number and then i want a 2d arry to be dynamically allocated
suppose user enters 25 , then the array will have 5 rows and 5 coloumns
how to do this
i suppose we have to do something like this
int **a;
for(int i=0;i<sqrt(n);i++)
for(int j=0;j<sqrt(n);j++)
a[j]=(int*)malloc(sizeof(int));
but it is giving a error like
invalid conversion from `int*' to `int'
a doesn't exist until you assign something to a. So, it would probably look like:
int rows = sqrt(n);int columns = n / rows;int i;int **a = malloc(sizeof(int*) * rows);for (i = 0; i < rows; ++i) a = malloc(sizeof(int) * columns);frobnicate(a, rows, columns);for (i = 0; i < rows; ++i) free(a);free(a);
what is this frobnicate(a, rows, columns);
error : 58 `frobnicate' undeclared (first use this function)
error : 58 `frobnicate' undeclared (first use this function)
It is a dummy name used to represent anything. It's purpose is not a call to the function, but to demonstrate how to use the array you just allocated.
ok ...
but still i cant understand the above code
int **a = malloc(sizeof(int*) * rows);
for (i = 0; i < rows; ++i)
a = malloc(sizeof(int) * columns);
i need a further explaination..
thanks in advance
but still i cant understand the above code
int **a = malloc(sizeof(int*) * rows);
for (i = 0; i < rows; ++i)
a = malloc(sizeof(int) * columns);
i need a further explaination..
thanks in advance
The first call to malloc allocates a number of pointers representing the rows (or columns) of the 2D array. The second set of calls to malloc in the loop allocates the individual columns (or rows). You need to do this becuase you cannot allocate arrays with more than one unknown dimension. If you need a 2D array with both dimensions unknown, you must allocate both dimensions individually.
The free-part is the same, only reverse. You must free exactly what you allocate.
The free-part is the same, only reverse. You must free exactly what you allocate.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement