我正从C++将我的一个项目转变为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
我敢打赌,你对应的C++函数具有不同的签名,或者它也在那里不行... – sth