![]() |
VOOZH | about |
In C, arrays and pointers are closely related and are often considered same by many people but this a common misconception. Array names are not a pointer. It is actually a label that refers to a contiguous block of memory where the elements are stored.
In this article, we will learn more about the array name and how it is similar and different from the pointers in C.
Below are the similarities between array name and pointers in C:
An array name can be used to represent the address of the first element of the array. For example, if arr is an array, arr can be used to refer to the address of arr[0].
Example
*ptr = 1 *arr = 1
Both array names and pointers support array subscript notation for accessing elements.
ptr[2] = 3
Pointer arithmetic can be applied in contexts involving both array names and pointers. But keep in mind that we cannot change the value of the array name. It is constant and will always refer to the same array.
Example
*(arr + 2): 3 *(ptr + 2): 3
Below are the differences between array name and pointers in C:
An array name represents a fixed-size collection of elements and refers to the memory location of the first element of the array. While a pointer is a variable that holds the memory address of another variable.
The memory size of an array is the total size of all its elements while the size of a pointer is fixed, typically 4 bytes on a 32-bit system and 8 bytes on a 64-bit system, regardless of the data it points to.
Example
Size of arr: 20 Size of ptr: 8
An array name is immutable in terms of reassignment. Once an array is declared, its name always points to the same memory location.
A pointer can be reassigned to point to different memory locations during its lifetime as long as it is not of const type.
Example
The following program will throw an error.
Output
main.c: In function ‘main’:
main.c:8:8: error: lvalue required as increment operand
8 | arr++;
| ^~
While an array name is not a pointer, it often behaves like one due to array-to-pointer decay. Understanding the differences and similarities between array names and pointers is crucial for effective programming in C and C++.