Pointers
Every variable lives somewhere in memory, at an address. A pointer is a variable that stores an address.
& gives an address, * follows it
C
#include <stdio.h>
int main() {
int age = 21;
int *p = &age; // p holds the address of age
printf("age = %d\n", age);
printf("*p = %d\n", *p); // the value p points to
*p = 30; // change age through the pointer
printf("age now = %d\n", age);
return 0;
}&agemeans "the address ofage".int *pdeclarespas a pointer to anint.*pmeans "the value at the address inp" (called dereferencing).
Changing a variable from a function
In the functions lesson, a function couldn't change the caller's variable because C passes copies. Pass the variable's address instead, and the function can reach the original:
C
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 1, y = 2;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y);
return 0;
}This is exactly why scanf("%d", &n) needs &n: scanf needs to know where to write the number.
Pointers and arrays
An array's name acts as a pointer to its first element, and adding to a pointer moves it along the array:
C
#include <stdio.h>
int main() {
int nums[4] = {10, 20, 30, 40};
int *p = nums; // same as &nums[0]
printf("%d\n", *p); // 10
printf("%d\n", *(p + 1)); // 20
printf("%d\n", p[2]); // 30: indexing works on pointers too
for (int i = 0; i < 4; i++) {
printf("%d ", *(p + i));
}
printf("\n");
return 0;
}*(p + i) and p[i] mean the same thing; array indexing is pointer arithmetic underneath.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.