← Back to C Course | Chapter 7: Pointers | Lesson 4 of 9

C Pointers & Arrays

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

c
#include <stdio.h>
int main() {
	int arr[3] = {1, 2, 3};
	printf("%d", *arr);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int arr[3] = {10, 20, 30};
	printf("%d", *(arr + 1));
	return 0;
}

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

c
#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;
}

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

c
#include <stdio.h>
int main() {
	int arr[3] = {1, 2, 3};
	int *ptr = arr;
	*(ptr + 1) = 99;
	printf("%d", arr[1]);
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.