Like every variable, a pointer must be declared before use, with a type that says what kind of object it points to. This section covers declaring pointers, giving them valid addresses, and three special kinds: pointers to pointers, null pointers and void pointers.
Declaring a pointer
Syntax
data-type *pointer-name;
int *ptr; declares ptr as a pointer to int. The type before the * is the type of the object pointed to, not the type of the pointer’s own value. That type tells the compiler how many bytes to read through the pointer and how to interpret them.
In a declaration, the * belongs to each name: int *p, q; declares p as a pointer and q as a plain int.
ptr = &qty; stores the address of qty in ptr. After that, *ptr is another name for qty: reading *ptr reads qty, and assigning to *ptr changes qty.
Uninitialised pointers
A pointer declared without a value holds garbage: it points to some unknown place. Writing through it changes memory that does not belong to the variable you intended.
Pointer to a pointer
A pointer is itself a variable with an address, so another pointer can point to it. int **pii; declares a pointer to a pointer to int.
int i = 100; int *pi = &i; int **pii = π
pii -----> pi -----> i 100 **pii is *pi is i
Each * follows one arrow: *pii is pi, and **pii is i.
Null pointers
The null pointer is the standard “points to nothing” value. Set a pointer to NULL when it has no valid target, and test it before use: if (ptr != NULL) { ... }. Dereferencing a null pointer is undefined behaviour and normally crashes the program at once, which is far easier to debug than a garbage pointer.
void pointers
A void * is a generic pointer: it can hold the address of an object of any type, but it carries no information about that type. It cannot be dereferenced directly; it must first be converted to a pointer of a real type.
Key takeaways
int *p; declares a pointer to int; p = &x; makes it point to x.
*p reads or writes the object pointed to.
An uninitialised pointer is dangerous; initialise to a valid address or NULL.
int **pp points to a pointer; void * is a generic pointer that needs a cast before use.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain what is wrong with int *p; *p = 25; and write a corrected version.
Show worked answer
p is declared but never given an address, so it holds a garbage value and points to an unknown location. *p = 25; writes 25 to that location, which is undefined behaviour: it may crash or silently corrupt other data. Corrected version: int x; int *p = &x; *p = 25;. Now p holds the address of a real variable, so the assignment stores 25 in x.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/pointers/declaring-and-assigning-pointers/ to read this page.