Reputation: 182
I am learning the basics of C++ and came across this question as I was learning pointers. I understand that *
is used to access the value of the address stored in the pointer. So if I were to do this:
int *p;
p = new int[5];
why is it that the second line would create an array in heap and store the address of the array in p
? We did not dereference p
in the second line by doing a *p
. As far as my limited knowledge tells me, doing p=value
would be storing that value in the pointer p
when we are supposed to store the address of that value in the pointer p
.
Upvotes: 0
Views: 403
Reputation: 7198
Understanding pointers may be hard.
Suppose there's a house, at "GreatStreet no 234". Nobody knows about this house.
Now person A, who lives somewhere else, is told about that house. The information is just the address of the house. There's a plus in the info: it says "it's a house, no other thing".
Same goes with pointers.
int *p;
p = new int[5];
int *p
is person A. At this moment he knows nothing, except that latter it will be informed about a house. That it is related to a house and not to a car is due to int
. A car would be float
instead.
int[5]
is the house, freshly built by new
action. This new
command not only creates the array, but it also returns the address, this is "GreatStreet no 234" (or its equivalent in heap position).
p= new...
tells person A about the address of the house.
The good thing with pointers is that not only you can work with "person A" (by p
) but also with its info about the house (by the asterisk in *p
).
So, you can change the house if you use the asterisk method (dereference) *p = 3
. But you can not change the address of the house.
If you change the info of the pointer p= ...
without asterisk, you're changing the address to another house.
Upvotes: 0
Reputation: 238321
We did not dereference p in the second line by doing a *p.
Which is a good thing. On the first line, the pointer was not initialised, so it doesn't point to anything. Attempting to access the imaginary pointed object by indirecting through a pointer that doesn't point to an object results in undefined behaviour.
By assigning the pointer without indirecting through it, the pointer itself is is modified rather than the pointed object.
As far as my limited knowledge tells me, doing a p=value would be storing that value in the pointer p
Which is exactly what we want to do, when that value is the address of an object.
P.S. The example leaks memory. Avoid using bare owning pointers. Use std::vector
to create a dynamic array.
Upvotes: 3