我正從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