vendredi 1 juillet 2016

C++ Pointer and Memory Allocation

I am teaching myself C++. It is my first programming language and I am struggling with the wording associated with the memory allocation of pointers.

Consider this statement:

int *p;
int x;
p = &x;
*p = 8;

          Value
&p        1400
p         1800
*p        8
x         8

&p is the memory address of p.

p is the memory address pointed to by the pointer p.

*p is the value of the memory address pointed to by the pointer p.

I understand this. However the book states:

p = &x stores the address of x in p. However, no new memory is allocated.

This is confusing. Memory has been allocated, else p would be undefined.

Now consider this statement:

int *p;
p = new int;
*p = 28;

Here, you dont need an additional variable to make *p valid and meaningful, because memory has been allocated.

So, I guess my question is:

What is the author's meaning of his statement, "Memory is not allocated.", when considering the code block?

Aucun commentaire:

Enregistrer un commentaire