Issue with pointers

Hi everybody, I am new to this site so please excuse me if my entering of the code doesn't come out aesthetically correct. I am working on an exercise for C++ regarding pointers and I have to find the issue with code. I am have a pretty good understanding of everything up to this point but pointers have been kind of working me. the code is...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int *p;
itn *q;

p = new int[5];
*p = 2;

for (int i = 1; i < 5; i++);
    p[i] = p[i - 1] +i;

q = p;

delete [] p;

for (int j = 0; j < 5; j++)
    cout << q[j] << " ";

cout << endl;


I'm pretty sure it has to do with the "delete [] p;" function. It seems to only delete the first two values of the array but not the rest. Is that the issue? Or is that caused by something happening earlier on in the program? Any help would be greatly appreciated and will help further expand my understanding of pointers.
The lifetime of the array ends at line 12. Accessing elements of that array at line 15 (which is what you're doing through the pointer q) invokes undefined behavior -- the program may crash and burn, may print some numbers, may do anything at all. A program with undefined behavior cannot be reasoned about in any meaningful way.

Also, at line 7, you have a stray semicolon, and line 2 is an obvious typo.
Last edited on
Oh yeah the stray semicolon was a typo as well. Thank you very much. That helped a lot. I figured the life of the array had ended but i was curious as to why it still output numbers. The undefined behavior explains it. Thank you!
Topic archived. No new replies allowed.