In this article, we will write a C program to print array elements using pointers. The program first takes the elements of the array from the user as input and then prints each element using pointers.
Sample Example:
Input:
Enter the size of the array: 5
Enter the array elements: 10 20 30 40 50
Output:
The Array Elements are: 10 20 30 40 50
In C programming, there are actually two ways you can access the elements of an array: First, using the array index and second using the pointers.
A pointer in C programming is a special type of variable that holds the memory address of another variable. It is declared by putting an asterisk symbol *
before the name of the pointer variable. For example, *ptr
, *myptr
, etc.
Now, if we talk about arrays in C, they do also use pointers behind the scenes. When you declare an array for eg. int arr[]
, the name of the array i.e. arr
is actually a pointer to the very first element of the array.
This means that arr[0]
is equivalent to *arr
, arr[1]
is equivalent to *(arr + 1)
, arr[2]
is equivalent to *(arr + 2)
and so on.
What this also means is that we can directly use the array name for eg. arr
or (arr + 1)
, etc. in the scanf()
function without the ampersand symbol &
to take the elements of the array as input from the user.
Let’s put all this together and write a C program to access the array elements using pointers:
// C program to access array elements using pointers #include <stdio.h> int main() { int arr[100], size; printf("Enter the size of the array: "); scanf("%d", &size); printf("Enter the array elements: "); for(int i = 0; i < size; i++){ scanf("%d", (arr + i)); } printf("The Array Elements are: "); for(int i = 0; i < size; i++){ printf("%d ", *(arr + i)); } return 0; }
Output:
Enter the size of the array: 5 Enter the array elements: 10 20 30 40 50 The Array Elements are: 10 20 30 40 50
In this program, we have created an array arr[]
of integer data type. The array name itself is used inside the scanf()
function to take the array elements from the user.
Note that we have used the expression (arr + i)
inside the scanf()
function without the ampersand &
symbol because the array name is already a pointer variable. So the &
symbol is no more required.
To access the array elements, we have first dereferenced the array by putting a *
symbol and then incremented it by 1 in each iteration of the for loop i.e. *(arr + i)
. Here
arr[0]
is equivalent to*(arr + 0)
and&arr[0]
is equivalent to(arr + 0)
.arr[1]
is equivalent to*(arr + 1)
and&arr[1]
is equivalent to(arr + 1)
.arr[2]
is equivalent to*(arr + 1)
and&arr[2]
is equivalent to(arr + 2)
.- …
arr[i]
is equivalent to*(arr + i)
and&arr[i]
is equivalent to(arr + i)
.
I hope you will find this article helpful. Thanks for reading.