Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of pointer to array

Tags:

c

I have learnt that the name of the array is actually the address of array_name[0]. 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?

like image 897
Shaw Ankush Avatar asked Jul 26 '26 16:07

Shaw Ankush


2 Answers

int *pointer_name = array_name;

declares a pointer to int that points to the first int of the array array_name.

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

declares a pointer to an array of 5 ints that points to the array array_name.

Addresses are the same but types not.

If you use pointer arithmetic on those you have, in the first case:

pointer_name++;

will just point to the second int of the array, while in the second case it will point just after the whole array.

like image 168
Jean-Baptiste Yunès Avatar answered Jul 28 '26 10:07

Jean-Baptiste Yunès


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;

and

int *pointer_name = array_name;

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

like image 30
P.P Avatar answered Jul 28 '26 08:07

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!