Pointers & Arrays
int numbers[5] = {10, 20, 30, 40, 50};
printf("%p\n", numbers); // address of the first element
printf("%p\n", &numbers[0]); // the exact same address
printf("%d\n", *numbers); // 10 - dereferencing gives the first value
This is why, as mentioned in Lesson 4, you never write &numbers when passing an array to scanf() — the array name already behaves like an address.
You can move a pointer forward through an array by adding to it — and C automatically scales the math by the size of the data type:
int numbers[5] = {10, 20, 30, 40, 50};
int *ptr = numbers;
printf("%d\n", *ptr); // 10
printf("%d\n", *(ptr + 1)); // 20 - moves forward one INT, not one byte
printf("%d\n", *(ptr + 2)); // 30
int numbers[5] = {10, 20, 30, 40, 50};
int *ptr = numbers;
for (int i = 0; i < 5; i++) {
printf("%d\n", *(ptr + i));
}
This produces exactly the same output as numbers[i] — in fact, numbers[i] is literally just shorthand the compiler translates into *(numbers + i) behind the scenes.
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
printArray(numbers, 5); // no & needed, and size must be passed separately
return 0;
}
Unlike single variables, arrays are effectively always passed by reference in C — the function receives the actual array's address, not a copy, so changes made inside the function do affect the original array.
Unlike a Python list, a C array passed into a function loses all information about its own size — the function only receives a pointer to the first element. If you forget to pass the size as a separate parameter, the function has no way to know when the array ends, and will happily read past its end into unrelated memory.
Write a function that takes an array and its size, and returns the largest value found in the array.
#include <stdio.h>
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int numbers[6] = {23, 67, 12, 89, 45, 33};
printf("Max: %d\n", findMax(numbers, 6));
return 0;
}