-1
我有一些代碼打算在更大的程序中使用,它獲取用戶的輸入,然後應該將該輸入寫入文件,但數據在寫入之前/到一個文件。C - char數組意外更改的內容
#include <stdio.h>
char *input();
void output(char text[1000]);
int main()
{
char text[1000]={'\0'}, *textPtr;
textPtr=text;
textPtr=input();
output(textPtr);
}
char *input()
{
char text[1000], *textPtr=text;
textPtr=text;
fflush(stdin);//Clears the newline character left by any prevoius scanf statements
scanf("%[^\n]s",textPtr);
return textPtr;
}
void output(char text[1000])
{
FILE *file;
printf("\nText before file statement:\n");
printf("%s\n",text);
//For some reason this line seems to trigger a change in 'text'
file=fopen("output.txt","a");
printf("\nText after file statement:\n");
printf("%s\n",text);
fprintf(file,"%s\n",text);
fclose(file);
printf("\nText after write and close statement:\n");
printf("%s\n",text);
}
與此類似圖像輸出功能,輸出的東西打印語句無論輸入
所以它打印的「文」到所需的內容中使用了這些內容直接之前然後它將這些內容替換爲空,然後在文本文檔中只寫一個換行符,然後在下一個打印語句中文本變成一個單獨的奇怪重音字符(每次程序運行時都會變化)。
所以我相信我有點濫用指針,或者我以一種奇怪的方式從函數返回char數組。
您也應該檢查fopen'的'返回值的參數。 – pzaenger
[返回指向自動變量的指針]的可能重複(http://stackoverflow.com/questions/1224042/returning-a-pointer-to-an-automatic-variable) –
'fflush(stdin);'調用undefined行爲,它沒有被定義爲適用於輸入流。 – Lundin