简体   繁体   中英

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(ie 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.

TL;DR Arrays are not pointers.

In your code, &name is a pointer to the array of 5 char s . 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM