我需要創建一個動態數組來存放我要從三個文件中讀取的字符串。我是C新手,並且我不太瞭解如何使用指針或分配內存。我想知道如果我正確地聲明我的陣列,並且我的calloc()
調用是正確的。因爲我使用的文件格式爲:我正確使用這個動態數組嗎?
word1
word2
word3 (and so on)
我只是假設從文件的話是超過50個字符(包括\0
)不再。
最終我需要對它們進行排序,但在嘗試之前我需要將它們放入數組中。感謝您提供的任何幫助。
這裏是我迄今爲止...
#include <stdlib.h>
#include <stdio.h>
int countWords(FILE *f){
int count = 0;
char ch;
while ((ch = fgetc(f)) != EOF){
if (ch == '\n')
count++;
}
return count;
}
int main(void){
int i;
int wordCount = 0;
int stringLen = 50;
FILE *inFile;
inFile = fopen("american0.txt", "r");
wordCount += countWords(inFile);
fclose(inFile);
inFile = fopen("american1.txt", "r");
wordCount += countWords(inFile);
fclose(inFile);
inFile = fopen("american2.txt", "r");
wordCount += countWords(inFile);
fclose(inFile);
printf("%d\n", wordCount);
char **wordList = (char **) calloc(wordCount, wordCount * sizeof(char));
for (i = 0; i < wordCount; i++){
wordList[i] = (char *) calloc(stringLen, stringLen * sizeof(char));
}
char ch;
int currentWord = 0;
int currentWordIndex = 0;
inFile = fopen("american0.txt", "r");
while ((ch = fgetc(inFile)) != EOF){
if (ch == '\n'){
currentWord++;
currentWordIndex = 0;
}
else
wordList[currentWord][currentWordIndex] = ch;
}
inFile = fopen("american1.txt", "r");
while ((ch = fgetc(inFile)) != EOF){
if (ch == '\n'){
currentWord++;
currentWordIndex = 0;
}
else
wordList[currentWord][currentWordIndex] = ch;
}
inFile = fopen("american2.txt", "r");
while ((ch = fgetc(inFile)) != EOF){
if (ch == '\n'){
currentWord++;
currentWordIndex = 0;
}
else
wordList[currentWord][currentWordIndex] = ch;
}
printf("%s\n", wordList[57]);
for (i = 0; i < wordCount; i++){
free(wordList[i]);}
free(wordList);
return 0;
}
+1與源代碼的有用和清楚的問題。 – pmg