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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With