Ok so I have some code from a study guide and I put it into a compiler and I don't completely understand the result.
#include <iostream>
using namespace std;
int main()
{
int *p, *p1;
p = new int[10];
p1 = p++;
for (int i=0; i<10;i++)
{
*p1 = i*10;
p1++;
}
for (int i=0; i<10;i+=2)
{
p[i] = i*100;
}
for (int i=0; i<5;i++)
{
cout << *p++ << " ";
}
}
I basically think I understand everything except for the line that reads p1 = p++;
I think that's just saying that p1
now points to the same array as p
but I don't exactly know what the p++
part of it does.
When I put it in a compiler I get 0 20 200 40 400
which I don't understand. Can someone explain what that one line means and then why I'm getting that output?
p = new int[10];
We allocate an array with space for 10 ints, and point p
at its head:
p-> 0:[ - ]
1:[ - ]
2:[ - ]
3:[ - ]
4:[ - ]
5:[ - ]
6:[ - ]
7:[ - ]
8:[ - ]
9:[ - ]
p1 = p++;
This seems a bit odd and isn't really good style. This copies the value of p into p1 (so it points where p1 was pointing) and then increments p to point to the next item in the array. It's generally a bad idea not to retain a pointer to the start of a dynamically allocated array, because it means you can't deallocate it. (In principle you can of course decrement the pointer back to the start, but to do that you need to know how many places to decrement, and it's a lot easier just to keep the original pointer. And if you think this is a lot of hassle, it is! That's why std::array and std::vector exist. But let's return to the question at hand...)
0:[ - ] <- p1
p-> 1:[ - ]
2:[ - ]
3:[ - ]
4:[ - ]
5:[ - ]
6:[ - ]
7:[ - ]
8:[ - ]
9:[ - ]
for (int i=0; i<10;i++)
{
*p1 = i*10;
p1++;
}
This loops ten times, and each time it does, it sets the value in the array pointed at by p1, and advances p1 one place. By the end, p1 is pointing one position past the end of the array. (That's okay, but only so long as nothing tries to read or write to that position.)
0:[ 0 ]
p-> 1:[ 10 ]
2:[ 20 ]
3:[ 30 ]
4:[ 40 ]
5:[ 50 ]
6:[ 60 ]
7:[ 70 ]
8:[ 80 ]
9:[ 90 ]
<- p1
for (int i=0; i<10;i+=2)
{
p[i] = i*100;
}
This is a bit more confusing. Remember that p is pointing at index #1 of the original array, not index #0. This loops five times, with i having values of 0, 2, 4, 6 and 8. Since p is already pointing at index #1 instead of #0, this actually updates indexes #1, #3, #5, #7 and #9 in the original array.
0:[ 0 ]
p-> 1:[ 0 ]
2:[ 20 ]
3:[ 200 ]
4:[ 40 ]
5:[ 400 ]
6:[ 60 ]
7:[ 600 ]
8:[ 80 ]
9:[ 800 ]
<- p1
for (int i=0; i<5;i++)
{
cout << *p++ << " ";
}
Finally this loops five times, each time outputting the element currently pointed at by p while also moving p to the next item.
0:[ 0 ]
1:[ 0 ] <
2:[ 20 ] <
3:[ 200 ] < These five elements were output.
4:[ 40 ] <
5:[ 400 ] <
p-> 6:[ 60 ]
7:[ 600 ]
8:[ 80 ]
9:[ 800 ]
<- p1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With