Pointers and arrays are closely related in C, and in many expressions an array name behaves like a pointer to its first element. However, they are not the same, and they differ in memory allocation, assignment, arithmetic, and several other operations.
- An array is a fixed-size collection of elements stored in contiguous memory locations, whereas a pointer is a variable that stores the address of another variable.
- Although array names often decay into pointers, arrays and pointers behave differently with operators like sizeof, &, assignment, and pointer arithmetic.
#include <stdio.h>
int main() {
int array[5] = {10, 20, 30, 40, 50};
int *pointer = array;
printf("First array element = %d\n", array[0]);
printf("First element using pointer = %d\n", *pointer);
printf("Size of array = %zu bytes\n", sizeof(array));
printf("Size of pointer = %zu bytes\n", sizeof(pointer));
pointer++; // Valid
printf("Pointer now points to = %d\n", *pointer);
// array++; // Invalid: Array name cannot be modified
return 0;
}
Output
First array element = 10 First element using pointer = 10 Size of array = 20 bytes Size of pointer = 8 bytes Pointer now points to = 20
Explanation
- An array stores a fixed collection of elements, whereas a pointer stores the memory address of another variable.
- Arrays have fixed memory and cannot be reassigned, while pointers can point to different memory locations and support pointer arithmetic.
- Although array names often behave like pointers, they differ in operations such as sizeof, assignment, and increment (++).
Difference Between Pointer and Array
| Array | Pointer |
|---|---|
| An array stores a fixed collection of elements of the same data type. | A pointer stores the memory address of another variable. |
| Memory for all array elements is allocated together. | A pointer occupies memory only for storing an address. |
sizeof(array) returns the total size of the entire array. | sizeof(pointer) returns the size of the pointer itself (4 or 8 bytes depending on the system). |
| The array name represents the address of its first element in most expressions. | The pointer variable contains an address that can point to different memory locations. |
| Array names cannot be assigned to another address after declaration. | Pointer variables can be assigned new addresses. |
Pointer arithmetic on an array name is not allowed (array++ is invalid). | Pointer arithmetic is allowed (pointer++ is valid). |
| Arrays have a fixed size once declared. | A pointer can point to different arrays or variables during program execution. |
Initializing char array[] = "abc" creates a writable character array containing the string. | char *pointer = "abc" points to a string literal, which should not be modified. |