Table of contents
No headings in the article.
In C, an array is a fixed-size collection of elements of the same type. A pointer is a variable that stores the memory address of a value or another variable. There are several key differences between pointers and arrays in C:
Array elements are stored contiguously in memory, while a pointer can point to any location in memory.
The size of an array is fixed, while the size of a pointer is determined by the system architecture (e.g. 32 bits or 64 bits).
An array name refers to the address of the first element in the array, but a pointer stores the address of a specific location in memory.
An array can be initialized with a list of values at the time of declaration, but a pointer must be assigned the address of an existing value or variable.
An array can be accessed using the subscript operator (e.g.
arr[i]
), while a pointer must be dereferenced using the indirection operator (e.g.*ptr
) to access the value it points to.
Here is an example of declaring and initializing an array and a pointer in C:
int arr[5] = {1, 2, 3, 4, 5}; // array of 5 integers
int *ptr = &arr[2]; // pointer to the 3rd element in the array
You can access the elements of the array using the subscript operator:
int a = arr[0]; // a is 1
int b = arr[2]; // b is 3
You can access the value pointed to by the pointer using the indirection operator:
int c = *ptr; // c is 3
You can also use the pointer arithmetic to access other elements in the array:
Copy codeint d = *(ptr + 1); // d is 4
int e = *(ptr - 1); // e is 2
It's important to note that pointers and arrays are closely related in C and can often be used interchangeably. For example, you can use an array name as a pointer to the first element in the array, and you can use a pointer as an array by using the subscript operator. However, it's generally a good idea to be explicit about whether you are using a pointer or an array to avoid confusion.