Monday, 9 March 2015

Pointers and Arrays in C


An array is a series of elements of the same data type. Pointers can be used to manipulate arrays rather than using an index. The name of an array points to the first element of the array. If you declare an array in the following manner:

int marks[5];

you can point to the first element of the array using either one of the following pointers:

marks //first element
&marks[0] //first element

Also the following pairs of pointers are equivalent:

marks+1 == &marks[1]
......
marks+4 == &marks[4]

Or you can use the array name to refer to the contents of the array elements like:

*(marks) //value of 1st element
*(marks+1) //value of 2nd element

Program 8.4 illustrates the use of array name, index and pointers.

/* Program-8.4 */

#include <stdio.h>
int main()
{
int marks[5]= {89, 45, 73, 98, 39};
printf("%d\n", marks); //memory address pointed by pointer
printf("%d\n", &marks[0]); //memory address of 1st element
printf("%d\n", *marks); //value pointed by pointer
printf("%d\n", marks[0]); //value of 1st array element
return 0;
}


No comments:

Post a Comment