user231243
user231243

Reputation: 11

Pointer to array and dynamic memory allocation

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 *));

Upvotes: 1

Views: 283

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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.

Upvotes: 2

Related Questions