【发布时间】:2013-01-25 04:55:42
【问题描述】:
我正在尝试将每个单词的单词和数量存储在struct word 的数组中
struct word{
char str[MAX_WORD_LENGTH];
int num;
}
inputFile = fopen("wordstat.txt", mode);
if(inputFile == NULL){
printf("Cannot open file\n");
return 1;
}
//scan through file to count number of possible words
while(fscanf(inputFile, "%s", scan)){
wordCount++;
}
rewind(inputFile);
struct word *words = malloc(wordCount * (sizeof *words));
如何访问字符串并将其存储到成员变量 str 中?在我做malloc之前需要初始化吗?
【问题讨论】:
-
如果您打算在访问它们之前全部设置
str值,则不必初始化它们,但如果您可能不会分配每个str,那么您可能想要使用calloc而是将所有内容归零。如果您稍后要写入值,它会慢一点并且没有必要。
标签: c arrays struct char malloc