Friday, July 29, 2016

C Basics - Pointer to an Array in C

An array name is a constant pointer to the first element of the array. For example,

int total[10];

total is a pointer to &total[0], which is the address of the first element of the array total. Thus, the following program fragment assigns ptr as the address of the first element of total,

int *ptr;
int total[10];

ptr = total;

It is legal to use array names as constant pointers, and vice versa. Therefore, *(total + 4) is a legitimate way of accessing the data at total[4].

#include <stdio.h>

int main () {

   /* an array with 5 elements */
   int total[5] = {10, 20, 30, 40, 50};
   int *ptr;
   int i;

   ptr = total;
 
   /* output each array element's value */
   printf( "Array values using pointer\n");
 
   for ( i = 0; i < 5; i++ ) {
      printf("*(ptr + %d) : %d\n",  i, *(ptr + i) );
   }

   printf( "Array values using balance as address\n");
 
   for ( i = 0; i < 5; i++ ) {
      printf("*(total + %d) : %d\n",  i, *(total + i) );
   }
 
   return 0;
}
The output of the above program would be:

Array values using pointer
*(ptr + 0) : 10
*(ptr + 1) : 20
*(ptr + 2) : 30
*(ptr + 3) : 40
*(ptr + 4) : 50
Array values using balance as address
*(total + 0) : 10
*(total + 1) : 20
*(total + 2) : 30
*(total + 3) : 40
*(total + 4) : 50



Related topics:
Pointers in C   |   Pointer Arithmetic in C   |   Returning Array from a Function in C   |   Array of Pointers in C   |   Pointer to Pointer in C   |   Pointers and Functions in C

List of topics: C Programming

No comments:

Post a Comment