ju**********@yahoo.co.in wrote:
What is the correct way of dynamically allocating a 2d array ?
I am doing it the following way. Is this correct ?
#include <stdlib.h>
int main(void)
{
int (*arr)(3);
I'm assuming you meant
int (*arr)[3];
arr = malloc(sizeof(*arr) * 4);
/* I want to dynamically allocate
int arr[4][3] */
I'm assuming you meant
int arr[3][4]
arr[2][3] = 100; /* Can I initialize the 3rd column of
2nd row in this manner ? */
}
Thanx in advance for any help ...
Well, it's different (never thought to do it that way before). It
appears to work, though. However, this method requires one dimension
be fixed. If you want to allocate a 2D array of int and be able to
specify both dimensions dynamically, here's one method:
#include <stdlib.h>
int **new2DIntArray(size_t rows, size_t cols)
{
int **arr;
int mallocError = 0;
size_t lastRow = 0;
arr = malloc(sizeof arr[0] * rows);
if (arr)
{
size_t i;
for (i = 0; i < rows && !mallocError; i++)
{
arr[i] = malloc(sizeof arr[i][0] * cols);
if (arr[i])
{
size_t j;
lastRow = i;
for (j = 0; j < cols; j++)
{
arr[i][j] = 0;
}
}
else
{
mallocError = 1;
break;
}
}
if (mallocError)
{
size_t i;
for (i = lastRow; i >= 0; i--)
{
free(arr[i]);
}
free(arr);
arr = NULL;
}
}
return arr;
}
int main(void)
{
int **arr1 = new2DIntArray(4,3); /* int arr[4][3] */
int **arr2 = new2DIntArray(3,4); /* int arr[3][4] */
/* etc. */
/* do something with arrays */
return 0;
}
You'll want to add another function to free up the arrays when you're
done with them, but that should be straightforward (basically it's the
if(mallocError) branch above).