This is quick question (I hope)... I get the pointer and double pointer use most of the time. I do have one question. If I just make a double pointer called int** ptr.
This is a pointer to a pointer to an integer, for this example. Without specifically creating a single pointer, is there an underlying single pointer to this double pointer? Would I be able to access that, if there is, without the need to create a single pointer separately?
thanks in advance
Bob
CodePudding user response:
Imagine that your memory is a looooong continuation of boxes. Each box has a unique number identifying it (it's address in this context).
When you write MyClass value{};
, it means that you want to store information, and you are requesting a box to store it into.
Now, you know someone that needs the value in this box, and you can't just clone it and send it to them. What you can do, is give the address of the box, for the other person to find it, and do something with the information.
This is what MyStruct* pointer_to_value = &value;
is, the address of the box. But you don't want to lose that address, so you store in a box as well. This box only has one thing: an address.
And you can do this indefinitely! (But you shouldn't ;) )
Next level would be MyStruct** poiunter_to_pointer_to_value = &pointer_to_value;
is, the address of the box (that happens to be an address to a previous box). But you don't want to lose that address, so you store in a box as well. This box only has one thing: an address.
If you want the information, you dereference, you follow the addresses back to the original box. You can't tell the difference between an address and data, just by looking inside the box, so you have the pointer type to tell you the difference. And a specific pointer doesn't care if it points to data or to other pointers. For the computer it's all data, but for the programmer pointers are data with a very specific meaning.
To answer your question:
If you have pointers to randomly assigned boxes, what would happen? It might be boxes with garbage values in them, or you are not allowed to access those boxes, etc...
In C you can create pointers to anything, but as all variables, they need to be initialised correctly to be of any use. If they don't point to valid values, you can "dangling pointers", which result in crashes, segfaults, undefined behaviour, etc. And you don't want to mess with any of those!
CodePudding user response:
Nope. Creating a pointer variable just creates a pointer variable. Nothing else.
Just like how int *ptr;
doesn't create an int
for ptr
to point to, nor does int **ptr;
create an int*
for ptr
to point to. It just creates ptr
.