Page 242 - DCAP404 _Object Oriented Programming
P. 242
Unit 11: Pointers and Dynamic Memory Management
int number; Notes
int *tommy = &number;
The behavior of this code is equivalent to:
int number;
int *tommy;
tommy = &number;
When a pointer initialization takes place we are always assigning the reference value to where
the pointer points (tommy), never the value being pointed (*tommy). You must consider that at
the moment of declaring a pointer, the asterisk (*) indicates only that it is a pointer, it is not the
dereference operator (although both use the same sign: *). Remember, they are two different
functions of one sign. Thus, we must take care not to confuse the previous code with:
int number;
int *tommy;
*tommy = &number;
that is incorrect, and anyway would not have much sense in this case if you think about it.
As in the case of arrays, the compiler allows the special case that we want to initialize the content
at which the pointer points with constants at the same moment the pointer is declared:
char * terry = “hello”;
In this case, memory space is reserved to contain “hello” and then a pointer to the first character
of this memory block is assigned to terry. If we imagine that “hello” is stored at the memory
locations that start at addresses 1702, we can represent the previous declaration as:
It is important to indicate that terry contains the value 1702, and not ‘h’ nor “hello”, although
1702 indeed is the address of both of these.
The pointer terry points to a sequence of characters and can be read as if it was an array (remember
that an array is just like a constant pointer).
Example:
We can access the fifth element of the array with any of these two expression:
*(terry+4)
terry[4]
Both expressions have a value of ‘o’ (the fifth element of the array).
LOVELY PROFESSIONAL UNIVERSITY 235