In this tutorial we will learn about the relationship between and array and pointers in C Programming. Here also we learn about declaring and accessing the array elements through pointers.
First simple Example of an Array:
#include<stdio.h> int main() { int a[5],i=0; printf("Enter the values in an array:\n"); for(;i<5;i++) { scanf("%d",&a[i]); } printf("Elements are:\n"); for(i=0;i<5;i++) { printf("%d\n",a[i]); } return 0; }
Output: Enter the values in an array: 10 20 30 40 50 Elements Are: 10 20 30 40 50
Then, How to print addresses of an array? By bellow example,
#include<stdio.h> int main() { int a[5],i=0; printf("Addresses are:\n"); for(i=0;i<5;i++) { printf("&a[%d]=%u\n",&a[i]); } printf("Address of a is %u",a); return 0; }
Output: &a[0] = 234678 &a[1] = 234682 &a[2] = 234686 &a[3] = 234690 &a[4] = 234694 Address of a is 234678
In the above example, we saw that the addresses of array elements are consecutive memory locations we get.
Means the base address is 234678 is an initial array element address and then next succeeding addresses are increment by 4 bytes. Because of the size of int 4 bytes (On Our Compiler).
Notice that, the address of “a” and first element “&a[0]” in an array is same.
From the above example &a[0] is equivalent to a. And, a[0] is equivalent to *a.
Similarly,
- &a[1] is equivalent to a+1 and a[1] is equivalent to *(a+1).
- &a[2] is equivalent to a+2 and a[2] is equivalent to *(a+2).
- ………..
- &a[i] is equivalent to a+i and a[i] is equivalent to *(a+i).
Example of Array And Pointer Using (x+i):
#include <stdio.h> int main() { int i, a[6], sum = 0; printf("Enter 6 numbers: "); for(i = 0; i < 6; ++i) { //Equivalent to scanf("%d", &a[i]); scanf("%d", a+i); //Equivalent to sum += a[i] sum += *(a+i); } printf("Sum = %d", sum); return 0; }
When we run the program the output will be:
Output Enter 6 numbers: 1 2 3 4 5 6 Sum = 21
Example of Array And Pointer For Accessing Individual Elements:
#include <stdio.h> int main() { int a[5] = {1, 2, 3, 4, 5}; int* ptr; // ptr is assigned the address of the third element ptr = &a[2]; printf("*ptr = %d \n", *ptr); // 3 printf("*(ptr+1) = %d \n", *(ptr+1)); // 4 printf("*(ptr-1) = %d", *(ptr-1)); // 2 return 0; }
The output will be the above code is:
#Output *ptr = 3 *(ptr+1) = 4 *(ptr-1) = 2
In this example, &x[2] is a address of third element assign to the pointer variable *ptr.
So when print *ptr the value is the third element of the array and we increment it *(ptr+1) goes to the next element and when decrement it *(ptr-1) moves to the previous element.
If you find any issue and interested to rewrite it then contact us.