我對C很陌生,我仍在學習基礎知識。我正在創建一個應用程序,它讀入一個文本文件並單獨分解這些單詞。我的意圖是計算每個單詞出現的次數。C中的循環崩潰
無論如何,下面代碼中的最後一個do-while循環執行得很好,然後崩潰。這個循環打印這個單詞(指針)的內存地址,然後打印這個單詞。它完成了這一點,然後在最後一次迭代中崩潰。我的意圖是將這個內存地址推入一個單獨的鏈表中,儘管它一旦停止崩潰。
此外,關於下面的數組大小隻是一個快速提及;我還沒有想出如何設置正確的大小來容納單詞字符數組等,因爲你必須在數組填充前定義大小,我不知道該怎麼做。因此,爲什麼我已經將它們設置爲1024
#include<stdio.h>
#include<string.h>
int main (int argc, char **argv) {
FILE * pFile;
int c;
int n = 0;
char *wp;
char wordArray[1024];
char delims[] = " "; // delims spaces in the word array.
char *result = NULL;
result = strtok(wordArray, delims);
char holder[1024];
pFile=fopen (argv[1],"r");
if (pFile == NULL) perror ("Error opening file");
else {
do {
c = fgetc (pFile);
wordArray[n] = c;
n++;
} while (c != EOF);
n = 0;
fclose (pFile);
do {
result = strtok(NULL, delims);
holder[n] = *result; // holder stores the value of 'result', which should be a word.
wp = &holder[n]; // wp points to the address of 'holder' which holds the 'result'.
n++;
printf("Pointer value = %d\n", wp); // Prints the address of holder.
printf("Result is \"%s\"\n", result); // Prints the 'result' which is a word from the array.
//sl_push_front(&wp); // Push address onto stack.
} while (result != NULL);
}
return 0;
}
請忽略壞的程序結構,正如我所說,我是新來的!
感謝
首先,這樣的:'持有人[N] = *結果;'可能是*不是*做你認爲的事。其次,當'strtok(NULL,delims)'由於結束標記條件而返回NULL時,你認爲這樣做是什麼? – WhozCraig 2013-03-28 11:47:19