A pointer is a variable that holds the address of another object. & takes an address, * follows one. Pointers are what make C fast, flexible — and dangerous.
Declare, take an address, dereference
#include <stdio.h>
int main(void) {
int x = 10;
int *p = &x; /* p holds the address of x */
printf("x = %d, *p = %d\n", x, *p);
*p = 20; /* write through the pointer */
printf("x = %d\n", x);
printf("p == &x ? %d\n", p == &x);
printf("sizeof p = %zu, sizeof *p = %zu\n", sizeof p, sizeof *p);
return 0;
}x = 10, *p = 10
x = 20
p == &x ? 1
sizeof p = 8, sizeof *p = 4| Expression | Meaning | Value here |
|---|---|---|
x | The int itself | 20 |
&x | Address of x (type int *) | e.g. 0x16fdff1ac |
p | The address stored in p | same as &x |
*p | The int at that address | 20 |
&p | Address of the pointer variable (type int **) | another address |
Printing addresses
#include <stdio.h>
int main(void) {
int a = 1;
double d = 2.0;
printf("&a = %p\n&d = %p\n", (void *)&a, (void *)&d);
return 0;
}NULL and pointer states
#include <stdio.h>
int find(const int *a, int n, int key, const int **where) {
for (int i = 0; i < n; i++)
if (a[i] == key) { *where = &a[i]; return 1; }
*where = NULL;
return 0;
}
int main(void) {
int nums[] = {4, 8, 15};
const int *hit;
if (find(nums, 3, 8, &hit)) printf("found %d at index %td\n", *hit, hit - nums);
if (!find(nums, 3, 99, &hit) && hit == NULL) printf("99 not found, hit is NULL\n");
return 0;
}found 8 at index 1
99 not found, hit is NULLDereferencing NULL
#include <stdio.h>
int main(void) {
int *p = NULL;
printf("%d\n", *p); /* segmentation fault */
return 0;
}What is the size of a pointer?
What is the difference between NULL, 0 and '\0'?
Why use pointers at all?