1
votes

How can one create 2-D array using pointer to array in C and dynamic memory allocation, without using typedef and without using malloc at time of pointer to array declaration? How do we typecast for pointer to array? In general how can we create a[r][c] , starting from int (*a)[c] and then allocate memory for "r" rows ?

For ex. If we need to create a[3][4] , Is this how we do ?

int (*a)[4];

a= (int (*) [4]) malloc (3*sizeof (int *));
1
I'm surprised nobody told this yet, but it's not good practice to cast the result of malloc() in C.Bregalad

1 Answers

2
votes

For ex. If we need to create a[3][4] , Is this how we do ?

int (*a)[4];

a= (int (*) [4]) malloc (3*sizeof (int *));

int (*a)[4] = malloc ( 3 * sizeof ( int [4] ) );

Or

int (*a)[4] = malloc ( 3 * sizeof ( *a ) );

Or

int (*a)[4] = malloc ( 12 * sizeof ( int ) );

The first form of initialization is more informative.