Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we allocate a pointer to an array

Tags:

c

I have been asked in an interview, there is an pointer to an array of 10 integers, something like this below.

 int (*p)[10];

How do you allocate it dynamically ??

This is something I have done

p=(int *)malloc(10*sizeof(int));

But it looks wrong because I am not doing the right typecast.

So I would like to know what's the type of *p ??

Like int *p ,p is of type int.

like image 320
Amit Singh Tomar Avatar asked Jan 18 '23 17:01

Amit Singh Tomar


1 Answers

Here is how to allocate:

p = malloc(sizeof *p);

or

p = malloc(sizeof (int [10]));

p is of type int (*)[10] and *p is of type int [10].

p is pointer to an array 10 of int and *p is an array 10 of int.

like image 118
ouah Avatar answered Jan 28 '23 03:01

ouah