pointer trouble

Hey, I'm having pointer trouble... My last function prints weirdly. I believe it of course has to do with the first function. I don't know why though.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int main()
{

int box[10];
int * p, * c,*p2 ;
p = box;
int k = 20;
c = &k;
*c =30;
int boxer[2];
p2 = boxer;
*p2 = 20;
p2++;
*p2 = 30;
cout << *--p2 << "  " << boxer[0] << endl;


cout << k << endl;
	for (int i = 0; i < 10; i++)
	{	*p = i;
		p++;
		
	}
for (int i = 0; i < 10; i++)
	cout << *(p+i);
cout << endl;
return 0;
}


EDIT: Note: if you change the first functions way of doing things to just one line -- *(p+i) = i; it works.
Last edited on
FYI, you don't have two functions there. You just have one and it is called main(). Everything else inside main are statements. I think you wanted to say "My last FOR statement prints weirdly". Just setting the record straight here.

After the FOR statement in line 22 has finished, p has been advanced 10 times. Since it started pointing to the first element of box, it now points one element after the 10th element of box, meaning it is pointing to an invalid memory location.

Then comes the second FOR statement in line 27. This one uses p untouched, as it was left by the previous FOR statement, meaning p points to invalid memory when this second FOR starts. It gets worse: As i advances, the FOR statement continues to print more and more invalid memory locations. So what is needed? Simple: Reset p back to the first element of the array before entering the FOR statment in line 27, or switch the FOR statements: Execute the FOR statement in line 27 before the one in line 22.
LOL i ment loops... haha. and thanks. That makes perfect sense. I wonder why I didn't see that.
Topic archived. No new replies allowed.