Shaw Ankush Shaw Ankush - 1 year ago 57
C Question

Initialization of pointer to array

I have learnt that the name of the array is actually the address of

. Then why does is require to add ampersand sign before the name of the array while initializing a pointer to the array.

int (*pointer_name)[5] = &array_name;

I have tried:

int *pointer_name = array_name;

and it works fine. What is the difference between the two other than the "type of pointer"?
And also what are the pros-cons of either of them. When to use them?
Does anyone of them has got any greater/ better functionality over other?

usr usr
Answer Source

Then why does is require to add ampersand sign [..]. I have tried : int *pointer_name = array_name; And it works fine.

Because the types are different.

  • &array_name is a pointer to an array of 5 ints and has type: int (*)[5].

  • array_name gets converted into a pointer to its first element when you assign it to pointer_name (which is equivalent to &array_name[0]) and has type: int*.

If array_name is an array of 5 ints then both:

int (*pointer_name)[5] = &array_name;


int *pointer_name = array_name;

are valid. Just how you'd access them later through these two pointers is different.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download