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