Array name as Pointers in C

When an array is declared in a c program actually a pointer is declared unknowingly. If we declare an array int a[5]. Basically, we are declaring a pointer ‘a’ that points to the first element of the array. It is carrying the base address (address of a[0]) of the array.

So, we can say that a is equivalent to &a[0]. So, we can conclude that the ith location can be defined by *(a+i) that is value at address (a+i).

The difference between the array name and the pointer variable is that, the address of the array name can never be changed it will always point to the first element of the array. But the pointer is quite flexible. It can point to somewhere else also.

Example

/* C program to understand array name as pointer */
/* www.codewindow.in */

int main() {
	int a[5], i;
  	for(i = 0; i < 5; ++i)
   		*(a + i) = i;			//array name is used as a pointer to store the value
  	
    printf("Printing elements: \n");
    
    for(i = 0; i < 5; ++i) 
   		printf("%d\n", *(a + i));
  	
	return 0;
}

Output

Printing elements:
0
1
2
3
4

Explanation:
In *(a+i)=i the index of the array element is stored as the value for that element. *(a+i) for the first iteration gives *(a+0)=a[0]=0. Similarly, for the next iteration it will return 1, as 1 is stored in a[1]. Simultaneously 2, 3, 4 will also be returned for the next iterations.


You Missed

Also Checkout


Leave a Comment

Your email address will not be published. Required fields are marked *