我不知道我的程序正在發生什麼,但我基本上有一個函數試圖從文件中讀取一串字符串,並將其傳遞迴主進行進一步處理。這裏是我的代碼:從字符串中使用垃圾值C使用C
char* readFile(FILE* fpFile)
{
// Local Declaration
char *ptr;
char temp[1000];
// Statment
fgets(temp, sizeof(temp), fpFile);
ptr = temp;
return ptr;
}// readFile
一旦函數返回指向main的指針,就會出現問題。我嘗試打印字符串,但是我只能得到正確的前幾行,並在它是垃圾之後。另外,如果我要在功能readFile
中打印ptr
,它將打印得非常好,並且傳回主打印的指針也可以正常打印。有什麼我失蹤了嗎?任何幫助,將不勝感激。
這裏是我得到
2000 1990
New York-No. NJ; 21199865 19549649
Los Angeles area; 16373645 14531629
Chicago area; 9157540 8239820
Washington-Baltimore; 7608070 6727050
San Francisco area; 7039362 6253311
Philadelphia-Atlantic City area; 6188463 5892937
Boston\240\365\277_\377
有應該是投入的量的兩倍的輸出,但它像回採的方式的四分之一。
噢,不! 你最好先看看: http://stackoverflow.com/questions/4824342/returning-a-local-variable-from-function-in-c – Mikhail 2013-05-03 04:14:04