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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Or 3 * sizeof(a[0]) in order to avoid to repeat the 4 compile time constant twice
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 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.
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 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]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.