【发布时间】:2011-09-29 22:41:32
【问题描述】:
我需要创建一个结构体wordStruct 的动态数组,其中包含一个字符串以及它在文本文件中出现的次数:
typedef struct wordStruct{
char word[50];
int count = 0;
}wordStruct;
我将通过读取文件中的字数得到我需要的数字,我们称之为wordCount。
struct wordStruct *wordList;
wordList = (wordStruct *)malloc(wordCount * sizeof(wordStruct));
这是为struct 数组分配内存的正确方法吗? calloc() 会是更好的选择吗?
int wordListIndex = 0;
char[50] inWord; // No word will be more than 49 characters + null terminator
for (i = 0; i < wordCount; i++){
fscanf(data, "%s", inWord);
for (j = 0; j < wordCount; j++){
if (strcmp(wordList[j].word, inWord) == 0){
wordList[j].count++;
break;
}
}
if (j == wordCount){
strcpy(wordList[wordListIndex].word, inWord)
wordListIndex++;
}
我知道这可能不是最有效的代码,但我的想法是否正确?即使这些数组位置中可能没有任何数据,我可以使用strcmp() 方法吗?我是结构的新手,我不确定我能做什么,不能做什么。
谢谢。
【问题讨论】:
-
如果你在 typedef'ing 它,你为什么要使用 struct 来声明一个 wordStruct?
-
您的第一个结构声明不是 C 代码。它在这里做什么?其余的代码也充满了奇怪的声明。
char[50] inWord;- 这是什么? -
我是新结构,我不确定正确的语法。
标签: c struct dynamic-memory-allocation