OK, first let me provide 2 programs:
Program 1:
#include <iostream>
using namespace std;
int main()
{
int a[5], i;
int *ptr;
ptr = a;
cout << "Enter the elements of the array:" << endl;
for (i = 0; i < 5; i++)
{
cin >> a[i];
}
cout << endl;
cout << "*ptr:";
for ( i=0 ; i<5 ; i++ )
{
cout << *ptr ;
*ptr++ ;
}
cout << "&a[i]:" << endl ;
for (i = 0; i < 5; i++)
{
cout << &a[i] << endl;
}
cout << endl ;
cout << "ptr:" << endl;
for (i = 0; i < 5; i++)
{
cout << (ptr+i) << endl;
}
return 0;
}
Output:
Enter the elements of the array: 1 2 3 4 5
*ptr: 12345&a[i]:
0018FF30
0018FF34
0018FF38
0018FF3C
0018FF40ptr:
0018FF44
0018FF48
0018FF4C
0018FF50
0018FF54
Program 2:
#include <iostream>
using namespace std;
int main()
{
int a[5], i;
int *ptr;
ptr = a;
cout << "Enter the elements of the array:" << endl;
for (i = 0; i < 5; i++)
{
cin >> a[i];
}
cout << endl;
cout << "*ptr:" << endl ;
for ( i=0 ; i<5 ; i++ )
{
cout << *(ptr+i) ;
}
cout << "&a[i]:" << endl ;
for (i = 0; i < 5; i++)
{
cout << &a[i] << endl;
}
cout << endl ;
cout << "ptr:" << endl;
for (i = 0; i < 5; i++)
{
cout << (ptr+i) << endl;
}
return 0;
}
Output:
Enter the elements of the array: 1 2 3 4 5
*ptr: 12345
&a[i]:
0018FF30
0018FF34
0018FF38
0018FF3C
0018FF40ptr:
0018FF30
0018FF34
0018FF38
0018FF3C
0018FF40
From the above programs, we can see that *ptr in both the cases displays the same output.
I know that the code in Program 2 is the correct way of incrementing when dealing with pointers.
BUT, the ptr in both the programs are not same. I am pretty sure that the for loop which is used to display *ptr in Program 1 is responsible for this mess. I want to know what is happening in the for loop to display *ptr in Program 1 because of which ptr is affected.