pointer_operator new

Hi,
this is my coding.

#include <iostream>

using namespace std;


int main()

{

int x, *p, *q;
p = new int[10];
q = p;
*p = 4;

for (int j=0; j<10; j++)
{
x = *p;
p++;
*p = x + j;
}

for (int k = 0; k < 10; k++)
{
cout << p[k] << " "; //edited
}
cout << endl;

return 0;
}

-------------------------------------------------
Based on theory,
The output should be
4 4 5 7 10 14 19 25 32 40
But now the output is
49 57943 4128964 4134664 0 0 0 0 0 0

so what wrong with my coding?

Last edited on
That can't possibly be the output, as you print the same value ten times.
Aside from that, you have an out-of-bounds access in the last iteration of the first loop and after it, p points past the array, so p[1] is two elements past the array, resulting in undefined behavior.
Athar, sorry I type wrongly...
Let I edit it again.
Yeah, but the problems remain. You have one out-of-bound access in the first loop and since you're modifying p, all 10 accesses in the second loop are out-of-bounds.
Athar, mean that cout<<p[0] will not output the 1st element array(which is created by operator new)?

why ? p[0] is not represent the 1st element of array?
I am confused... T.T
Can explain to me?
Thanks.
It won't, because you changed what p points to in the first loop (p++;).
You incremented p ten times, so it now points to a location beyond the last element.
Last edited on
So, how to modify the coding if i wan to output as 4 4 5 7 10 14 19 25 32 40?

I know do this way can output as following,
for (int k = 0; k < 10; k++)
{
cout << *q << " ";
q++;
}
cout << endl;

But is there other ways to output it?
Topic archived. No new replies allowed.