Sub topic 3
Pointer Basics: Declaring, Taking Addresses, and Dereferencing
Assume you know basic C syntax, variables, operators, functions, and how to compile a small program. This chapter focuses on the working model of a pointer and the errors that commonly appear in GATE-style questions.
A pointer is a variable whose value is the address of another object. The pointer's type describes the type of object found at that address.
| Expression | Meaning |
|---|---|
| `int *p` | Declare `p` as a pointer to `int` |
| `&x` | Address of `x` |
| `*p` | Object reached through pointer `p` |
| `p = &x` | Store the address of `x` in `p` |
Declaring and using a pointer
The address-of operator, &, produces an address. The dereference operator, *, follows an address and accesses the object stored there.
#include <stdio.h>
int main(void) {
int value = 10;
int *p = &value;
printf("%d\n", value);
printf("%d\n", *p);
*p = 25;
printf("%d\n", value);
return 0;
}p points to value, so *p and value designate the same integer. Assigning 25 through *p changes value itself. The output is:
10
10
25The declaration int *p means that dereferencing p produces an int. The star belongs to the declarator, so these declarations declare two pointer variables:
int *p, *q;This declaration declares one pointer and one ordinary integer:
int *p, n;A pointer should point to a compatible type. An int * should normally store the address of an int, while a char * should normally store the address of a char. The type tells the compiler how to interpret the bytes and how pointer arithmetic will work.
The pointer itself versus the pointed-to object
The pointer occupies storage too. p is the pointer value, while *p is the integer reached through that value.
A pointer can be assigned NULL, a special value that means it points to no object. Testing before dereferencing is essential:
int *p = NULL;
if (p != NULL) {
printf("%d\n", *p);
}Dereferencing NULL, an uninitialized pointer, or a pointer to an object whose lifetime has ended causes undefined behavior. The program might crash, print an unexpected value, or appear to work by accident.
Exercise
After int x = 7; int *p = &x; *p = *p + 3;, what are the values of x and *p?
Show answer
Both are 10 because p points to x, and the assignment changes the pointed-to object.