2

C++

int arr[5] = {1, 2, 3, 4, 5};
int (*p)[5] = &arr;

I know p is a pointer which points to an array with 5 elements, but when I try to print the address:

cout << p << "  " << *p << "  " << &arr << endl;

It gives me:

0x7fff50c91930  0x7fff50c91930  0x7fff50c91930

Question:

How could p equals *p? And now that p equals to &arr, why *p != arr[0]? What exactly does the value p and *p hold?

Yriuns
  • 755
  • 1
  • 8
  • 22

4 Answers4

1

enter image description here

It would be more clear to imagine that p points to the whole memory block of 5 int. So if there is a ( p + 1 ) it would point to the next memory block.


This then help answer your questions.

How could p equals *p?

p is pointer to array[5] that is initialized to point to arr[5]

*p is the value of the first array element - which is the address of arr[5]. And because the name of the array is the address of the first element. So when you print p and *p they are the same.

And now that p equals to &arr, why *p != arr[0]?

*p is the address of the first array element - which means the address of the whole arr[5] memory block. On the other hand, arr[0] is the first element of the array that p points to, so it's a real value (1) not an address.

What exactly does the value p and *p hold?

As your first question, both of them hold the address of the whole arr[5] memory block.

artm
  • 17,291
  • 6
  • 38
  • 54
0

first of all 'int' this is int type 'int*' this is int pointer type so int arr[5] = {1, 2, 3, 4, 5};//declare and initialize array of five integers int* p[5] ;//declare array of five integer pointers

pointers store only a reference. when we de-reference it by using * it gives the actual value stored at that reference.

int* is a type and only * is a operator(de-reference operator)

int (*p)[5] = &arr;// by doing this you are declaring array of five integer pointers and each pointer is initialing with starting reference of arr.

to get the values of arr by using integer pointer you can use p[0][0]//1 p[0][1]//2 and so on and same goes for pointers p[1], p[2] and so on

Abdullah Raza
  • 600
  • 3
  • 9
0

The name of an array usually evaluates to the address of the first element of the array, but there are two exceptions:

  1. When the array name is an operand of sizeof.
  2. When the array name is an operand of an unary & (address of).

In these 2 cases, the name refers to the array object itself.

MarianD
  • 13,096
  • 12
  • 42
  • 54
0

The name of the array evaluates to the address of the array .
So arr evaluates to &arr. But the types will be different.

Try this -
auto ar1 = arr; auto ar2 = &arr; auto ar3 = p; auto ar4 = *p;

ar1 will be of type int*.
ar2 will be of type int(*)[5]

Here you can see that ar4 and ar1 are the same type and ar2 and ar3 are the same type.

Superman
  • 159
  • 1
  • 6