【发布时间】:2017-03-30 14:53:01
【问题描述】:
现在我正在跨两个 .cpp 文件处理两个函数。假设我正在使用一个名为 someStruct 的结构:
struct someStruct {
int num;
}
A.cpp:
int main() {
someStruct *a = NULL;
bool ret;
ret = foo(a);
std::cout << a->num; // should print 5
}
B.cpp:
bool foo(someStruct *a) {
someStruct *b = someFunction(); // points to an instance of someStruct on the stack
// note that b->num should hold 5
// need something here
// ATTEMPT 1:
a = new someStruct(*b);
// ATTEMPT 2
a = (someStruct *)malloc(sizeof(someStruct));
a = memcpy(a, b, sizeof(someStruct));
}
我想要完成的是让主函数中的a 最终指向someStruct 的实例,该实例与foo() 中的结构指针b 具有相同的值。
我列出的尝试都没有奏效。
【问题讨论】:
-
Find a good beginners book 并阅读references。或者,不要在
main函数中声明指向someStruct的指针,并在将a传递给foo时使用地址运算符,然后在foo中使用解引用和赋值(如@ 987654335@). -
someStruct *b = someFunction(); // points to an instance of someStruct on the stack- 这听起来像是即将导致未定义的行为(如果你的函数在本地分配了struct,它的生命周期在函数返回时结束) -
不要在 C++ 中使用
malloc。 -
foo(a);不会改变main()的a的值,它是一个空指针。a->num尝试取消引用空指针。如果不更改foo()签名,更改其正文将无济于事。 -
只复制整个对象,不用担心动态分配和指针。
标签: c++