I just start learning C++. I thought I can access an integer array by using pointer arithmetic method. why does the first program work but the second one does not???

#include<iostream>
using namespace std;
int main()
{
 int array [5], i, *p;
 for (i = 0; i < 5; i++)
  array [i] = i;
 
 for (i = 0; i <5; i++)
  cout << array [i] <<' ';
 cout << "\n";
 p = array;
 cout << *p << ' ' << *(p+1) <<  ' ' << *(p+2) << ' ' << *(p+3) << ' '
  << *(p + 4);
 return 0;
}
#include<iostream>
using namespace std;
int main()
{
 int array [5], i, *p;
 for (i = 0; i < 5; i++)
  array [i] = i;
 
 for (i = 0; i <5; i++)
  cout << array [i] <<' ';
 cout << "\n";
 p = array;
 for (i = 0; i < 5; i++)
 {
  *p = *p * *p * *p;
  p++;
 }
 for (i = 0; i <5; i++)
  cout << array [i] << ' ' ;
 cout << "\n";
 
 cout << *p << ' ' << *(p+1) <<  ' ' << *(p+2) << ' ' << *(p+3) << ' '  << *(p + 4);
 return 0;
}

Recommended Answers

All 4 Replies

What do you expect to happen? After you increment 'p' in your third loop, it points past the last element of the array, so you're bound to get garbage data on your last outputs.

wel there is no syntax errors in the program ! but about logical that depends on your output !
just tell us what are you tryin to do ! or what do u expect for an output !
and by the way try to sperate the for loop from other statements
by puttin brackets
example :

for(startexpression;testexpression;countexpression)
{ //brackets!!
block of code;
} //brackets !!!

Your Code

for (i = 0; i <5; i++)
cout << array [i] << ' ' ;
cout << "\n";
cout << *p << ' ' << *(p+1) << ' ' << *(p+2) << ' ' << *(p+3) << ' ' << *(p + 4);

Thank you, for your response:)
So, each time I have to reset the pointer to point the begining of the array in order to display the contents of the array like this.....(That completely makes sense)
by the way, I might post another stupid question like this....please be patient with me.
Thank you!!

#include<iostream>
using namespace std;
int main()
{
 int array [5], i, *p;
 for (i = 0; i < 5; i++)
  array [i] = i;
 
 for (i = 0; i <5; i++)
  cout << array [i] <<' ';
 cout << "\n";
 p = array;
 for (i = 0; i < 5; i++)
 {
  *p = *p * *p * *p;
  p++;
 }
 for (i = 0; i <5; i++)
  cout << array [i] << ' ' ;
 cout << "\n";
 
[B]p = array;
[/B] 
 cout << *p << ' ' << *(p+1) <<  ' ' << *(p+2) << ' ' << *(p+3) << ' '  << *(p + 4);
 return 0;
}

dont worry hehe lol its good to learn sumffin after all !
i'm a newbie as wel !
cheers MAte

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.