The table that illustrates the relationship between pointers and arrays from 0D (scalar) to 3D. This table will help clarify how pointers and arrays are related in C, which can be a complex topic.
Dimension | Array Declaration | Pointer Declaration | Relationship | Example Usage |
---|---|---|---|---|
0D (Scalar) | int x; | int *p; | p = &x; | *p = 5; sets x to 5 |
1D | int arr[5]; | int *p; | p = arr; or p = &arr[0]; | p[i] is equivalent to arr[i] |
2D | int arr[3][4]; | int (*p)[4]; | p = arr; | p[i][j] is equivalent to arr[i][j] |
3D | int arr[2][3][4]; | int (*p)[3][4]; | p = arr; | p[i][j][k] is equivalent to arr[i][j][k] |
Additional notes:
0D (Scalar):
- A pointer can store the address of a single variable.
- Dereferencing the pointer (
*p
) accesses the value of the variable.
1D Array:
- An array name decays to a pointer to its first element.
- Pointer arithmetic works with the size of the base type.
2D Array:
- A 2D array is an array of 1D arrays.
- A pointer to a 2D array is a pointer to its first 1D array.
3D Array:
- A 3D array is an array of 2D arrays.
- A pointer to a 3D array is a pointer to its first 2D array.
Key Concepts:
- Array-to-pointer decay: In most contexts, an array name is converted to a pointer to its first element.
- Pointer arithmetic: Adding 1 to a pointer moves it to the next element, considering the size of the type it points to.
- Multi-dimensional arrays: Pointers to multi-dimensional arrays need to specify all dimensions except the first.