1
votes

I have following pointer to array variable.

 int (*p)[3];
 int a[3]  = { 1,2,3 } ;  
 int b[3]  = { 11,22,33 } ;  
 int c[3]  = {111,222,333} ;

I want to store these 3 array into variable p. How i have to allocate the memory for p and How should i store these 3 array into p like array of pointer. Whether is this possible ...? and How..?

Note:

p = (int (*)[])malloc(3);
Now this p is capable of pointing three integer array which size 3 . How i have to assign these a,b,c to this p ?

.

2
I'm afraid I didn't understood the question. Could you precise the complete type ? Such as : an array of pointers to int, or an array of pointers to an array of int ? - Clement Bellot
The malloc in your code allocates 3 bytes, it's not capable of pointing three integer array as you expect, because the size of a pointer is at least 4 bytes on any modern computer. - littleadv
Correction : you mean p = (int (*)[])malloc(3*sizeof(int*)); - Clement Bellot

2 Answers

1
votes

You don't need to allocate memory, it's allocated when you declare your array of pointers. Each pointer should point to the memory already allocated, but a, b, c are allocated automatically/statically, so you don't need to worry about that. Just assign them to the members of the array p and you're done.

If p is a pointer to array, then code should be:

int **p = malloc(sizeof(int*)*3);
...
p[0] = a; p[1] = b; p[2] = c;
...
free(p); /* when done*/

Declaring int *p[3] creates array of pointers, not pointer to array.

edit

If you want a pointer to an array then you can do this:

int a[3];
int *p = a;

And don't forget - you can use a on its own as a pointer to array it represents, where needed, you don't need a separate variable.

0
votes
int* p[3];
int a[3] = { 1,2,3 } ;
int b[3] = { 11,22,33 } ;
int c[3] = { 111,222,333} ;

p[0] = a;
p[1] = b;
p[2] = c;

That's it.

Edit 1

A pointer to array ?

int** p;
int a[3] = { 1,2,3 } ;
//...
p = &a;

Edit 2

And a array of pointers to array of int :

int** p[3];
int a[3] = { 1,2,3 } ;
//...
p[0] = &a;
//...