Array address VS pointer-to-pointer: Not the same?

I worked 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 a static pointer) pointing to the very first index of the array. right?

So, I'm trying to create another pointer that may contain the address of the array name (for example, a pointer to another pointer, which in my case is the name of the array)

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 am using Code Blocks as an IDE.

+5
source share
2 answers

TL DR Arrays are not pointers.

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

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

or,

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

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

+8
source

If you want to use a pointer to a 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; } 

greetings.

+2
source

Source: https://habr.com/ru/post/1243893/


All Articles