0
char list[] = "World";
char *ptr = list + 2;
char **p = &ptr;

The question: Why is &ptr of type char**? I understand that p points to a pointer to an array but isn't the address of ptr a char*?

I have looked at Is an array name a pointer?, is it possible that the array is considered a pointer as well in this case?

Community
  • 1
  • 1

6 Answers6

4

Is array considered a pointer also?

No, pointers and arrays are distinct types. The confusion arises partly because in many cases pointers can decay to arrays, and in functions, array-like parameters are adjusted to pointers.

Why is &ptr of type char**?

Because ptr is of type char*. Applying the address-of operator to an object of a type gives you a pointer to that type.

I understand that p points to a pointer to an array

No, it points to a pointer, which points to an element of an array.

A pointer to an array is a different type altogether. For example, here a real pointer to an array is made to point to an array:

int a[8];
int (*arr)[8] = &a;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

You have to follow things step-wise to easily understand this.

char* ptr is a pointer to char because it is pointing to a char.


What is p pointing at?

It is pointing at a char*. Therefore, it is a pointer to a pointer to a char. That is p is of type char**.

Haris
  • 12,120
  • 6
  • 43
  • 70
1

&ptr is a char ** simply because ptr is a char*. list is not a pointer, it's an array. But ptr is declared as char *, so it's a pointer.

ptr is initialised from a pointer list + 2. The expression list + 2 uses the operator +, which performs the array-to-pointer conversion on its operands (if applicable). Therefore, when evaluating list + 2, a temporary pointer to char is created from list using the array-to-pointer conversion. Then another temporary pointer is created by adding 2 to the first one, and this second temporary is then used to initialise ptr.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

An array's name "decays" into a pointer to its first element under most circumstances.

In this case, the array consists of 2 bytes. Its name list is a char * pointing to the W.

Consequently, list + 2 points to the r. This pointer is stored into ptr, a char * as well.

A char * is a pointer to char. Consequently, a char ** is a pointer to a pointer to char, and that's exactly what &ptr is.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

Array is not a pointer. It is an array. However, array can decay to pointer in certain contexts, of which most notable is passing an array to a function.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
0

A pointer is also the first element of an array, so the address of the first element of the array and the pointer of the array would be the same

Supachai Abusali
  • 143
  • 1
  • 1
  • 6