C Pointers & Arrays
In this page:
Array Name as a Pointer
This is why sizeof(arr) and sizeof(arr[0]) behave differently even though arr itself 'looks like' a pointer in expressions -- the array name only decays into an actual pointer value when it's used in most expressions, but sizeof still sees the full array type.
Example: Array Name as a Pointer
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
printf("%d", *arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Elements using Pointers
Both notations compile down to the exact same machine instructions, so choosing between arr[i] and *(arr + i) is purely a matter of readability -- most C code favors bracket notation for clarity except in performance-sensitive pointer-walking code.
Example: Accessing Elements using Pointers
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
printf("%d", *(arr + 1));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Scanning Arrays with Pointer Increments
This pattern (ptr = arr; while (...) { ...; ptr++; }) avoids recomputing an address from scratch on every access the way arr[i] technically does, which mattered more on older compilers that didn't optimize indexing as aggressively as modern ones do.
Example: Scanning Arrays with Pointer Increments
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
int *ptr = arr;
for (int i = 0; i < 3; i++) {
printf("%d ", *ptr);
ptr++;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Array Elements via Pointers
*(ptr + i) = newValue and arr[i] = newValue produce identical results -- both ultimately compute an address and write to it, so which style you use is again a matter of preference and context.
Example: Modifying Array Elements via Pointers
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
int *ptr = arr;
*(ptr + 1) = 99;
printf("%d", arr[1]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Comparing Pointers
Comparing pointers from two different arrays (or two unrelated variables) is technically undefined behavior in C, even though it will often work by accident -- only compare pointers that both point somewhere within the same array or one past its end.
Example: Comparing Pointers
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
int *p1 = &arr[0];
int *p2 = &arr[2];
printf("%d", p1 < p2);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: