Pointers and arrays
Read · 1 of 4
Arrays are addresses
Used in an expression, an array name like a becomes the address of a[0]. That's why functions can change arrays you pass them: they receive the address, not a copy.
If p points at an element, p + 1 points at the next one (C moves by the size of an int, not by one byte). *(p + i) is the same as p[i], and a[i] is really *(a + i).
Read this lesson as text
An array's name is the address of its first element, and p + 1 is the next element.
Arrays are addresses
Used in an expression, an array name like a becomes the address of a[0]. That's why functions can change arrays you pass them: they receive the address, not a copy.
If p points at an element, p + 1 points at the next one (C moves by the size of an int, not by one byte). *(p + i) is the same as p[i], and a[i] is really *(a + i).
Moving a pointer
#include <stdio.h>
int main() {
int a[5] = {10, 20, 30, 40, 50};
int *p = a;
p += 2;
printf("%d %d %d\n", *p, *(p + 1), p[-1]);
return 0;
}What does this print?
- 30 40 20
- 12 13 11
- 30 31 29
Show the answer
30 40 20 p starts at a[0] and moves 2 elements to a[2] (30). p + 1 is a[3], and p[-1] is a[1].
Exercise: Sum with a pointer
Complete int sum(int *p, int n) so it adds the n ints starting at p without using square brackets: move the pointer, or use *(p + i).
Exercise: Reverse in place
Write void reverse(int *a, int n) that reverses the array itself (no second array), by swapping from both ends towards the middle. Read n (1 to 100) and n numbers, reverse, and print them.