An array is collection of similar type of data stored in sequence order. For example, let us consider the following code block
int A[5]={2,3,4,5,6};
all the element of the array A[5] are stored in sequence. In modern day compilers an integer can take to byte of memory to store integer data and it looks like this
Let us consider a variable 'X"int x=10;
int *ptr;
ptr=x;
If you want print the value of 'X' using pointer we can do this as
printf('%d",*ptr); // gives x value located in address location 300.
If we de-reference the pointer as 'ptr+1', then we are trying to print
printf('%d",*(ptr+1)) // it will gives an error. We don't know what is stored in location 302.
One of the property of the array is " an array name is actually a pointer to its first element". When we are de-referencing the array name, we are de-referencing the first element of the array.
Example:
int A[5]={2,3,4,5,6};
One create a pointer using arrays as
1. ptr=A;
2. ptr=&A[0];
If you want to print the array elements, use pointer increment arithmetic.
Example-1:
Write a C program to read values into array and print them using pointers.
void main()
{
int a[10],i;
int *ptr;
ptr=a;
printf(" enter values into array");
for(i=0;i<10;i++)
scanf("%d",ptr++);
printf("array elements are ");
for(i=0;i<10;i++)
printf("%d",ptr++);
getch();
}
Example-2:
Write a C program to read values into array and print them in reverse order using pointers.
void main()
{
int a[10],i;
int *ptr;
ptr=a;
printf(" enter values into array");
for(i=0;i<10;i++)
scanf("%d",ptr++);
printf("array elements are ");
for(i=0;i<10;i++)
printf("%d",*(--ptr));
getch();
}

0 comments :
Post a Comment
Note: only a member of this blog may post a comment.