Theory
Which one is dangerous?
Three pointers:
int *a = &marks;
int *b = NULL;
int *c;
c is never given a value. Which one is the most dangerous to dereference?
Think first
Your guess first
Type the letter and your reason.
Show the answer
c. It holds leftover garbage, so *c touches some unknown place: a wild pointer. *b is an error too, but if (b != NULL) can test first. Always initialize a pointer, to a target or to NULL.
Theory
One pointer per type
int *pi = &marks;, float *pf = &perc; and char *pc = &grade; each match their target. The type matters because dereferencing uses it to know how many bytes to read and how to read them: usually 4 bytes as an int, 1 byte as a char.
Practical
The pointer drill
#include <stdio.h>
int main() {
int marks = 78;
float perc = 78.5;
char grade = 'A';
int *pi = &marks;
float *pf = &perc;
char *pc = &grade;
printf("%d %.1f %c", *pi, *pf, *pc);
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Why must a pointer to a float be declared float * and not int *?
- The type tells * how many bytes to read and how
- It is only a naming convention
- Float pointers are kept in a special, separate part of memory
- An int pointer cannot hold a large address
Show the answer
The type tells * how many bytes to read and how
Every pointer holds an address; the type tells * how to read it. The wrong type reads the right place the wrong way: garbage.
Theory
NULL and void *
NULL means "points nowhere yet", and code can check it. void *vp, a generic pointer, can hold the address of any type, but it cannot be dereferenced until you cast it: *(int *)vp.
Think first
Count the pointers
How many pointers does int* a, b; declare?
Show the answer
One: a is a pointer, but b is a plain int. The * belongs to the name, not to the type, so write int *a, *b; for two pointers.
Practical
Exam-style: predict the output
#include <stdio.h>
int main() {
int x = 7;
void *vp = &x;
int *ip = (int *)vp;
*ip = *ip + 3;
printf("%d %d", x, *(int *)vp);
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Exam-style: what is the output of the program above?
- 10 10
- 7 10
- 10 7
- A compile error
Show the answer
10 10
vp and ip both hold x's address. Adding 3 through ip makes x 10, and *(int *)vp reads that same box.
Summary
Key takeaways
- Match the pointer type to its target:
int *,float *,char *. - Initialize every pointer, to a target or to NULL; never leave it wild.
void *holds any address but needs a cast before*.- Memory hook: a blank address slip beats a random one.