Pointers & Arrays
Pointer and Array Relationship
In C, arrays and pointers are closely related. The array name usually represents the address of the first element. Because of this, array elements can be accessed using both index notation and pointer notation.
arr[i] is internally similar to *(arr + i). Both access the same element.
Array Name as Pointer
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
printf("Address of first element = %p\n", (void*)&arr[0]);
printf("Array name address = %p\n", (void*)arr);
printf("First element = %d\n", *arr);
printf("Third element = %d\n", *(arr + 2));
return 0;
}arr behaves like a pointer in expressions, but it is not a modifiable pointer variable. You cannot write arr++, but you can write ptr++.
Pointer Arithmetic with Arrays
When an integer pointer is increased by 1, it moves to the next integer element, not the next byte. The compiler automatically uses the size of the data type.
#include <stdio.h>
int main() {
int marks[] = {85, 90, 78, 92};
int *p = marks;
for(int i = 0; i < 4; i++) {
printf("marks[%d] = %d\n", i, *(p + i));
}
return 0;
}Passing Arrays to Functions
When an array is passed to a function, actually the address of its first element is passed. Therefore, changes made inside the function can affect the original array.
#include <stdio.h>
void update(int *a, int n) {
for(int i = 0; i < n; i++) {
a[i] = a[i] + 5;
}
}
void display(int a[], int n) {
for(int i = 0; i < n; i++) {
printf("%d ", *(a + i));
}
}
int main() {
int arr[] = {10, 20, 30};
update(arr, 3);
display(arr, 3);
return 0;
}Summary
arrnormally gives the base address of the arrayarr[i]and*(arr+i)access the same value- Pointer arithmetic moves according to data type size
- Arrays passed to functions can be handled using pointers
- Array name is not a modifiable pointer, so
arr++is invalid
Write programs to find sum, maximum, minimum and reverse of an array using pointers.
Frequently Asked Questions
What is the relationship between pointers and arrays in C?
a and &a[0] refer to the same address. This is why you can use pointer notation like *(a + i) to reach a[i]. Arrays and pointers are closely linked, though an array name itself cannot be reassigned.Is an array name a pointer in C?
a = a + 1; on an array name, whereas you can with a real pointer. So it is pointer-like, not a true pointer.What is pointer arithmetic on an array?
p + 1 always points to the following item.Why do arrays passed to functions become pointers?
What does *(a + i) mean in C?
*(a + i) is the pointer form of a[i]. a + i computes the address of the i-th element, and the * reads the value stored there. The two notations are completely equivalent and produce the same result.