What are the key differences between pointers and arrays in C language?
Core Differences:
-
Memory Allocation
- Arrays allocate contiguous memory space on stack or static storage
- Pointers are variables storing address information, can point to any memory location
-
sizeof Operator
cint arr[10]; int *ptr = arr; sizeof(arr); // Returns 40 (10 * sizeof(int)) sizeof(ptr); // Returns 8 (pointer size on 64-bit system) -
Assignment Operations
- Array names cannot be assigned, are constant addresses
- Pointers can be reassigned to point to different addresses
-
Operator Precedence
- Array subscript
[]has higher precedence than dereference* *ptr++dereferences then increments pointer(*ptr)++increments the value pointed to
- Array subscript
-
Parameter Passing
- Arrays decay to pointers when passed as parameters
- Cannot determine actual array size inside function
Common Pitfalls:
- Confusing type differences between
&arrandarr - Misusing pointer arithmetic causing out-of-bounds access
- Forgetting array names decay to pointers in expressions