'What is meaning of (*x++) in c++?
#include <iostream>
using namespace std;
class base {
public:
int* x, y;
base(int xx = 0, int yy = 0) {
x = new int[4];
for (int i = 0; i < 4; i++)
x[i] = 1;
(*x++) = xx;
y = yy++;
}
~base() { delete[] x; }
};
class Derived :public base {
public:
Derived(int xx, int yy) : base(xx), base1(yy) {
cout << (*(this->x)) << " " << this->y << " " << (*
(base1.x)) << " " << base1.y << " ";
}
~Derived() {}
private:
base base1;
};
int main() {
Derived objDev(32, 33);
return 0;
}
I have problem with understand it. Because i think it should give output as "33 0" but gave "1 0" and also i write in some std::cout for controlling in constructor body, and saw x[3] is -33686019 after '''(*x++) = x; ''' part. How could it be possible? how *x++ can change x[3] and why is this value? and also compiler give error. doesn't *x++ mean what is x point, increase it? so when after assign xx to (*x++) wouldn't it be 32+1=33? please help
Solution 1:[1]
x = new int[4]; creates an array of 4 int and sets x to point to the beginning of them. Because x is going to change, let’s call this array A, which will not change.
Then x[0] refers to the first element of this array, x[1] is the second, x[2] is the third, and x[3] is the fourth. So far x[0] and A[0] are the same thing, and so are the pairs x[1] and A[1], x[2] and A[2], and x[3] and A[3].
(*x++) is grouped as ( * (x++) ). x++ does two things. It produces the value of x, and, as a side effect, it increments x. Since x++ produces the value of x, *(x++) is the int that x points to before the increment.
This means that (*x++) = xx; stores x in the first element of the array, but it changes x to point to the second element, which is A[1].
Once x points to the second element, then x[0] is A[1], x[1] is A[2], x[2] is A[3], and x[3] is beyond the end of the array. x[-1] would be A[0].
So, where the code sends (*(this->x)) to cout, it is sending A[1], which has 1 in it. That explains why you got output of “1”.
When you looked at x[3], you were looking beyond the array. What is there could be some other value the program has worked with, completely unrelated to what is in the array. But accessing an element beyond array bounds can cause various problems with programs other than just giving a wrong value.
In the destructor, delete[] x; is wrong because x has been changed and no longer has the original address of the array. You could use delete [] --x; or delete [] x-1; to recalculate the original address. However, if a program has some need to use a pointer into the middle of an array, it is more common to store the base address and never change it and create a separate pointer into the middle. That is usually less error prone and easier for other programmers to follow.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Postpischil |
