Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of array VS pointer-to-pointer : Not the same?

I was working with pointers and came up with a problem. So far I know that when we create an array of any data type, then the name of the array is actually a pointer (maybe static pointer) pointing towards the very first index of the array. correct?

So what I'm trying to achieve is to create another pointer that may hold the address of the array name(i.e a pointer towards another pointer which in my case is the array name)

For Example:

char name[] = "ABCD";  // name holding the address of name[0]
char *ptr1 = name;      // When this is possible
char **ptr2 = &name;    // Why not this. It give me error that cannot convert char(*)[5] to char**

I'm using Code Blocks as IDE.

like image 586
Syed Ahmed Jamil Avatar asked Feb 25 '16 20:02

Syed Ahmed Jamil


People also ask

How is an array of pointer different from pointer of array?

Here is a list of the differences present between Pointer to an Array and Array of Pointers. A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer.

Does the address of a pointer change?

You can't change the address of a pointer (or of any variable). Once you declare the variable, it's address is firmly set, once and forever. You can, however, change the value of a pointer, just as easily as you can change the value of an int: x = 10 or p = &t.

Does pointers have its own address?

The main feature of a pointer is its two-part nature. The pointer itself holds an address. The pointer also points to a value of a specific type - the value at the address the point holds.

Why address of array is the same?

The pointer to the array has the same address value as a pointer to the first element of the array as an array object is just a contiguous sequence of its elements, but a pointer to an array has a different type to a pointer to an element of that array.


2 Answers

TL;DR Arrays are not pointers.

In your code, &name is a pointer to the array of 5 chars. This is not the same as a pointer to a pointer to char. You need to change your code to

 char (*ptr2)[5] = &name;

or,

char (*ptr2)[sizeof(name)] = &name;

FWIW, in some cases (example, passing an array as a function argument), the array name decays to the pointer to the first element in the array.

like image 66
Sourav Ghosh Avatar answered Oct 11 '22 14:10

Sourav Ghosh


If you want to use pointer-to-pointer, you can use this:

int main(void){
  char name[] = "ABCD";
  char *ptr1 = name;
  char **ptr2 = &ptr1;
  std::cout << *ptr1 << std::endl;
  std::cout << **ptr2 << std::endl;
}

cheers.

like image 25
Sujay Phadke Avatar answered Oct 11 '22 14:10

Sujay Phadke