In: Computer Science
How do you dereference a pointer? Explain the difference between a dereferenced pointer and the pointer itself.
What is a Pointer?
A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address. Pointers are essential for dynamic memory allocation.
Declaring pointers:
Pointer declarations use the * operator. They follow this format:
typeName * variableName;
int n; // declaration of a variable n
int * p; // declaration of a pointer, called p
In the example above, p is a pointer, and its type will be specifically be referred to as "pointer to int", because it stores the address of an integer variable. We also can say its type is: int*
The type is important. While pointers are all the same size, as they just store a memory address, we have to know what kind of thing they are pointing TO.
double * dptr; // a pointer to a double
char * c1; // a pointer to a character
float * fptr; // a pointer to a float
Pointer dereferencing:
Once a pointer is declared, you can refer to the thing it points to, known as the target of the pointer, by "dereferencing the pointer". To do this, use the unary * operator:
int * ptr; // ptr is now a pointer-to-int
// Notation:
// ptr refers to the pointer itself
// *ptr the dereferenced pointer -- refers now to the TARGET
Suppose that ptr is the above pointer. Suppose it stores the address 1234. Also suppose that the integer stored at address 1234 has the value 99.
cout << "The pointer is: " << ptr; // prints the pointer
cout << "The target is: " << *ptr; // prints the target
// Output:
// The pointer is: 1234 // exact printout here may vary
// The target is: 99
Difference between a dereferenced pointer and the pointer itself:
- Pointers can iterate over an array, you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.
- A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access it's members whereas a reference uses a ..
- A pointer is a variable that holds a memory address. Regardless of how a reference is implemented, a reference has the same memory address as the item it references.
- References cannot be stuffed into an array, whereas pointers can be.