Arrays Are Addresses in Disguise
This would have saved me a semester. An array in C is barely a thing. It is a row of values sitting next to each other, and the name of the array is the address of the first one. That’s it. Very little going on.
int arr[5] = {10, 20, 30, 40, 50};
printf("%p\n", arr); // the address of arr[0]
printf("%p\n", &arr[0]); // same address. Same.Five ints, four bytes each, side by side. So the address of any element is arithmetic: start at the first, step forward. That is exactly what the square brackets do, and they have been doing it behind your back the whole time.
arr[2] // 30
*(arr + 2) // 30. Same thing, written honestly.arr[2] is shorthand for *(arr + 2). Take the first address, move forward two, follow the arrow. The bracket is pointer arithmetic with an asterisk on the end. The compiler literally rewrites one as the other. Literally.
One subtlety, and it is the reason pointers have types. arr + 2 does not move two bytes. It moves two ints, eight bytes, because the compiler knows what arr points at. A char * steps one byte. A double * steps eight. The type on a pointer is not decoration. It is the stride. Big difference.
This is also why handing an array to a function “loses the size.” You did not hand over the array. You handed over the address of the first element, which is one number. The function has no idea what comes after it. So real C programmers pass the length too, and every array function in the standard library has that second argument for this reason.
int sum(int *a, int n) {
int total = 0;
for (int i = 0; i < n; i++)
total += a[i]; // or *(a + i). Same thing.
return total;
}Strings are the same idea with one trick. A C string is an array of char that ends in a zero byte, '\0'. The zero is how a function knows where the string stops without being told. Walk forward until you hit it.
int length(const char *s) {
int n = 0;
while (*s) { // stop at the '\0'
n++;
s++; // one char forward
}
return n;
}Read that loop with the two questions from Part 3. *s: what is here? s++: move forward. That is the entire loop. People make it very complicated. It is not complicated.