Arrays and Pointers
Arrays and pointers are different but connected.
Example:
int A[5] = {2,4,5,8,1};
- stored contiguously
- base address =
&A[0]
Address and value mapping
Address:
&A[i] == (A+i)
Value:
A[i] == *(A+i)
So [] is syntactic sugar.
Arrays and Pointers Diagram
Demonstrates how arrays and pointers are related, including base address concept, memory layout of elements, and pointer arithmetic like A[i] == *(A+i)
Why A++ is invalid?
Array name is constant base address (non-modifiable lvalue).
A++; // ❌
But pointer is modifiable:
int *p = A;
p++; // ✅
sizeof array vs pointer
sizeof(A) // full size
sizeof(p) // pointer size
Array Decay (Passing array to function)
When passed to function, array becomes pointer.
int sum(int A[], int n) { ... }
Inside function:
sizeof(A) == sizeof(int*)
Character arrays and strings
C strings must be null terminated.
char s[] = "Hello"; // includes \0
strlen vs sizeof
strlen(s) // 5
sizeof(s) // 6
Array vs pointer for string literal
char c1[] = "Hello"; // modifiable copy
char *c2 = "Hello"; // read-only literal
c2[0]='A' is undefined behavior.
Pointer to array (array pointer)
Normal pointer:
int *p = A;
Pointer to full array:
int (*pa)[5] = &A;
Pointer arithmetic:
p+1→ next intpa+1→ next whole array