#include<iostream.h>
void main()
{
int arr[5]={10,20,30,40,50};
int *ptr,i;
ptr=arr;
for(i=0;i<5;i++)
{
cout<<*(ptr+i)<<"\t";
*(ptr+i)=*(ptr+i)+5;
}
cout<<endl;
for(i=0;i<5;i++)
cout<<arr[i]<<endl;
}
Output:
10 20 30 40 50
15 25 35 45 55
Pointers and arrays
There is a close correspondence between array and pointers. An array name is very much like a pointer but there is a difference between them. the pointer is a variable that can appear on the left side of an assignment operator. In all other respects, both the pointer and the array version are the same.
Pointer and single dimensional array
Consider the following declaration.
int arr[5];
int *ptr;
The variable arr is a type of integer array of 5 elements. The address of the first element can be referred as &arr[0]. So the following is a valid statement,
ptr=&arr[0];
or
ptr=arr;
arr and &arr[0] both the expression refers the address of the first element in the array. If the pointer is incremented to the next data element, then the address of the incremented value of the pointer will be same as the value of the next element.
For example
ptr+2 is equal to &arr[3]
void main()
{
int arr[5]={10,20,30,40,50};
int *ptr,i;
ptr=arr;
for(i=0;i<5;i++)
{
cout<<*(ptr+i)<<"\t";
*(ptr+i)=*(ptr+i)+5;
}
cout<<endl;
for(i=0;i<5;i++)
cout<<arr[i]<<endl;
}
Output:
10 20 30 40 50
15 25 35 45 55
Pointers and arrays
There is a close correspondence between array and pointers. An array name is very much like a pointer but there is a difference between them. the pointer is a variable that can appear on the left side of an assignment operator. In all other respects, both the pointer and the array version are the same.
Pointer and single dimensional array
Consider the following declaration.
int arr[5];
int *ptr;
The variable arr is a type of integer array of 5 elements. The address of the first element can be referred as &arr[0]. So the following is a valid statement,
ptr=&arr[0];
or
ptr=arr;
arr and &arr[0] both the expression refers the address of the first element in the array. If the pointer is incremented to the next data element, then the address of the incremented value of the pointer will be same as the value of the next element.
For example
ptr+2 is equal to &arr[3]
No comments:
Post a Comment