This is how my code looks like:
int main()
{
int a[] = {1,23,5,56,7,5};
int *p2 = a;
size = sizeof(a)/sizeof(a[0]);
int *p1 = new int[size];
cout << "sizeof " << size << endl;
int i = 0;
while(p2 != a+size )
{
*p1++ = *p2++;
}
cout << p1[1] << ' ' << p1[3];
return 0;
}
cout << p1[1] << ' ' << p1[3]; outputting me values which are not the same as in a[1] and a[3]. Can anyone explain me why this is happening ?
Your
whileloop modifiesp1. After the loop is done,p1will point to the end of the new array (in fact, it’ll point to the next position after the end). To solve the problem, keep a copy of the originalp1.