Define a pointer and explain the address and dereference operators.
5 marks
Answer in brief
A pointer variable stores a pointer value. A valid object pointer can be used to access an object indirectly.
Declaration
int number = 10;
int *p = &number;
Address operator
&number produces the address of number. The declaration stores that address in p. The star in int *p declares a pointer type; it does not read the object at that point. The pointer and the pointed-to integer are separate objects.
Dereference operator
In an expression, *p accesses the integer to which p points. Reading *p initially gives 10. Assigning *p = 25 changes number itself to 25. It does not change which object p identifies.
Example trace
The program first prints the value through *p. It then assigns through *p and prints number. The second output is 25, demonstrating that direct access through number and indirect access through p reach the same object.
Important points
Initialise a pointer before using its stored value.
Dereference only a pointer that identifies a suitable live object.
Do not dereference NULL, a one-past-end position or an invalid pointer.
Use %p with an object pointer converted to void * when displaying an address; the displayed form depends on the implementation.
Complexity
A direct pointer dereference and assignment to a fixed-size object take O(1) work in the usual model. A pointer does not automatically allocate the object it is expected to identify.
Diagram or flowchart
Define a pointer and explain the address and dereference operators. · Download diagram
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int number = 10;
int *p = &number;
printf("Before = %d\n", *p);
*p = 25;
printf("After = %d\n", number);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Before = 10
After = 25
Related exam questions
Related questions in the pointer basics category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.