1

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 *));
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
user231243
  • 11
  • 3
  • I'm surprised nobody told this yet, but it's [not good practice to cast the result of `malloc()` in C.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Bregalad Apr 14 '15 at 10:53

1 Answers1

2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Or `3 * sizeof(a[0])` in order to avoid to repeat the `4` compile time constant twice – Bregalad Apr 14 '15 at 10:51
  • That was really useful, but what if we are said NOT to use malloc at time of pointer to array declaration(as referred in the question) , though we may use it in next line just after declaration ? And as we say that in int *ptr1; data type of ptr1 is int * and in int **ptr2; data type of ptr2 is int ** , similarly what would we say if someone asks about the data type of ptr3 and ptr4 in int (*ptr3)[7]; and int *ptr4[9]; respectively ? – user231243 Apr 14 '15 at 14:16
  • @user231243 You may at first declare the pointer and in some other statement assign to it the address of allocated memory. What is the problem? As for ptr1, ptr2 and so on I have understood nothing. – Vlad from Moscow Apr 14 '15 at 14:27
  • Even though it is not considered a good practice to type cast the result of malloc in C . Having declared int (*a)[4]; I am confused at this step --> a=(......)malloc(sizeof(int *)) , what to write in place of "(......)" ? And that I was asking about :- What are the date type of ptr3 and ptr4 in the declarations int (*ptr3)[7]; and int *ptr4[9]; respectively ? – user231243 Apr 14 '15 at 14:55
  • @user231243 Very strange question. I showed already all in my post. What is not clear? As for declarations int (*ptr3)[7]; and int *ptr4[9]; then they are pointers respectively to arrays of type int[7] and int[9] – Vlad from Moscow Apr 14 '15 at 15:06
  • I got it. Sorry for the trouble and thanks a lot ! :) – user231243 Apr 14 '15 at 16:26