7.2 Pointers and Arrays
An array name is essentially a pointer to the first element. So arr and &arr[0] are the same address, and you can even take the array's address without writing &.
int arr[] = {4, 1, 6, 7};
int *p = arr; // same as &arr[0]
printf("%d\n", *p); // 4
printf("%d\n", *(p + 2)); // 6Pointer arithmetic
When you add to or subtract from a pointer into an array (such as p++ or p -= 2), it does not move the address by one byte; it moves by the size of the pointer's type. For example, if p is an int * and an int takes 4 bytes, then p + 1 increases the address by 4.
So *(p + i) equals arr[i], and you can also write p[i]. You can walk the whole array with a pointer:
for (int *it = arr; it < arr + 4; it++) {
printf("%d ", *it);
}Arrays and functions
When you pass an array to a function, what you actually pass is the address of the first element, so the function receives a pointer. Inside the function, sizeof gives the size of a pointer, not the array length. That is why you usually pass the length as a separate parameter.
int search(int *arr, int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1; // not found
}
int main(void) {
int arr[] = {4, 7, 1, 3, 9, 2};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", search(arr, n, 3)); // 3
return 0;
}sizeof(arr) / sizeof(arr[0]) only works where the array itself lives; once the array decays to a pointer, it no longer gives the length.