C Programming: Memory, Pointers and the Stack · Pointers
An array name acts as a pointer to its first element, and p++ moves to the next element, not the next byte.
#include <stdio.h>
int main(void) {
int nums[4] = {10, 20, 30, 40};
int *p = nums; /* an array name becomes a pointer to its first element */
int first = *p;
p++; /* moves to the next int, not the next byte */
int second = *p;
int third = *(nums + 2); /* same as nums[2] */
int total = 0;
for (int *q = nums; q < nums + 4; q++) {
total += *q;
}
printf("%d %d %d %d\n", first, second, third, total);
return 0;
}nums is created on the stack with the value [10, 20, 30, 40].first is created on the stack with the value 10.second is created on the stack with the value 20.total is created on the stack with the value 0.q is created on the stack with the value → nums.q changes from → nums to → nums[1].total changes from 10 to 30.q changes from → nums[1] to → nums[2].total changes from 30 to 60.q changes from → nums[2] to → nums[3].total changes from 60 to 100.q goes out of scope and disappears.10 20 30 100.0.