【发布时间】:2011-08-19 08:55:49
【问题描述】:
我正在将我的一个项目从 C++ 转换为 C,并且事情进展顺利,因为我一开始并没有使用很多 C++ 功能。但是我遇到了一个特殊的问题,我设法在一个小型测试程序中复制了该问题。对我来说没有意义,所以我会尝试用代码来解释。
typedef struct foo
{
int num1;
float num2;
char* name;
}foo;
//This function allocates and initializes a foo object
foo* Initfoo()
{
foo* f = malloc(sizeof(foo));
f->num1 = 1024;
f->num2 = 3.14;
f->name = malloc(100);
strcpy(f->name,"eleos re paidia");
//Just before returning here by checking the f pointer we can see
// it is initialized correctly
return f;
}
void afunctest(foo* f)
{
///... suppose this function does stuff before ...
//here it initializes the foo pointer
f = Initfoo();
///...and after here suppose the function also does more stuff..
//by checking at this point in the program the pointer is still initialized
//correctly to what InitFoo initialized it to
int asd =5;
}
int main()
{
foo* f = 0;
//should do stuff and also initialize the foo* f
afunctest(f);
//when we check here the pointer f is still 0 as if afunctest() function never ran
int asd = 5;
return 0;
}
所以基本上简单地说,我们声明了一个 foo 指针并将其初始化为零。然后我们将该指针传递给 afunctest() 函数,该函数应该做一些事情并初始化它以供以后使用。在 afunctest() 函数内部,它似乎已正确初始化,但一旦我们回到 main(),它的值仍然为 0,就好像该函数从未运行过一样。
起初我认为这是我原始程序中的一个非常复杂的错误,因为它变得非常复杂,但能够在这里复制它意味着我错过了与 C++ 相比在 C 中使用指针的一些基本知识。你能指出这一点吗?我究竟做错了什么?提前感谢您的任何反馈。
P.S.:我的编译器是 Windows 7 下的 GCC。
【问题讨论】:
-
我敢打赌你对应的 C++ 函数有不同的签名,否则它也不会在那里工作......