struct mystruct{
int* x;
float *y;
string *z;
mystruct(int* a,float* b, string *c): x(a), y(b), z(c){}
};
void* create(){
int a = 1;
float b = 2.2;
string c = "aaa";
mystruct x(&a, &b, &c);
void* p = &x;
return p;
}
void print(void *p){
mystruct* p1 = static_cast<mystruct*>(p);
cout << *p1->x << " " << *p1->y << " "<<*p1->z<< endl;
}
int main(){
cout << sizeof(mystruct) << endl;
void* p1 = create();
print(p1);
return 0;
}
代碼的輸出是這樣的:24 1 2.76648e + 19 \ 203 \ 304] \ 303fffff \ 204UH \ 211 \ 345H \ 201 \ 354 \ 220H \ 211}。 \ 270H \ 211。 我猜想是這樣的:24 1 2.2 aaa無效*鑄造得到意想不到的輸出
我猜這個void *指針轉換出了問題,但我找不出原因。有人可以幫忙嗎?
您返回指向*局部變量*的指針。一旦函數退出,局部變量超出範圍,並且不再存在。指向這些局部變量的指針將失效。試圖取消引用該指針會導致[*未定義行爲*](http://en.cppreference.com/w/cpp/language/ub)。你解除引用四個這樣的無效指針。總之,這個問題與你的演員無關。 –
當你返回並使用'p'時,你整個程序的行爲是不確定的。 – StoryTeller
https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope?noredirect=1&lq=1 – Mat