Pointers & Arrays
Arrays and pointers are closely related in C.
An array name works like a constant pointer to its first element,
and pointer arithmetic provides powerful ways to access array data.
Relationship Between Pointers & Arrays
In C, the name of an array represents the base address of the array.
a→ base address of array&a[0]→ address of first element*(a)→ value of first element*(a + i)→ value of ith elementa[i]is same as*(a + i)
Pointer to an Array Element
A pointer can point to any element inside an array:
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[0];
Pointer Arithmetic
p + 1→ moves to next elementp - 1→ moves back one element- Pointer increments by the size of its data type
- Works only inside same array range
Advantages of Using Pointers with Arrays
- Efficient element access
- Fast traversal
- Used in dynamic arrays (malloc)
- Required in strings & matrices
- Used in function parameter passing
10 Examples of Pointers & Arrays
Example 1 – Basic Pointer to Array
#include <stdio.h>
int main(){
int a[3] = {10, 20, 30};
int *p = a;
printf("%d", *p); // 10
return 0;
}
Example 2 – Access Using Pointer Arithmetic
#include <stdio.h>
int main(){
int a[3] = {5, 7, 9};
int *p = a;
printf("%d", *(p + 1)); // 7
return 0;
}
Example 3 – Print Full Array Using Pointer
#include <stdio.h>
int main(){
int a[5] = {1,2,3,4,5};
int *p = a;
for(int i = 0; i < 5; i++)
printf("%d ", *(p + i));
return 0;
}
Example 4 – Modify Array Using Pointer
#include <stdio.h>
int main(){
int a[3] = {10, 20, 30};
int *p = a;
*p = 99;
printf("%d", a[0]); // 99
return 0;
}
Example 5 – Pointer to Specific Element
#include <stdio.h>
int main(){
int a[4] = {2,4,6,8};
int *p = &a[2];
printf("%d", *p); // 6
return 0;
}
Example 6 – Using Array Index With Pointer
#include <stdio.h>
int main(){
int a[4] = {3,6,9,12};
int *p = a;
printf("%d", p[2]); // 9
return 0;
}
Example 7 – Pointer Traversing Backward
#include <stdio.h>
int main(){
int a[4] = {10,20,30,40};
int *p = &a[3];
printf("%d", *(p - 2)); // 20
return 0;
}
Example 8 – Sum of Elements Using Pointer
#include <stdio.h>
int main(){
int a[5] = {1,2,3,4,5};
int *p = a;
int sum = 0;
for(int i=0; i<5; i++)
sum += *(p + i);
printf("Sum = %d", sum);
return 0;
}
Example 9 – Pointer to Array vs Array of Pointers
#include <stdio.h>
int main(){
int a[3] = {10,20,30};
int *p = a; // pointer to array
printf("%d", *p);
return 0;
}
Example 10 – Passing Array to Function Using Pointer
#include <stdio.h>
void show(int *p){
for(int i=0; i<4; i++)
printf("%d ", p[i]);
}
int main(){
int a[4] = {7,14,21,28};
show(a); // array decays to pointer
return 0;
}
Practice Questions
- Explain how array name works as a pointer.
- What is pointer arithmetic? Give examples.
- How can we modify array elements using pointers?
- Difference between
a[i]and*(a + i). - Write a program to find largest element using pointers.
Task:
Write a program using pointers to reverse an array without using a second array.