我正在尝试将单词和每个单词的数量存储在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 之前是否需要对其进行初始化?
最佳答案
struct word *words = malloc(wordCount * (sizeof *words));
有效地创建word
结构的一维数组,您可以使用数组表示法words[i].str
或指针表示法访问该数组(words + i)->str
访问条目“i”。
要存储字符串(例如从 scanf
调用返回的字符),请将它们复制到您的 word
结构中
fscanf( inputFile, "%s", scan );
strncpy( words[i].str, scan, MAX_WORD_LENGTH );
当您执行 malloc 时,每个结构字
中的字符串的内存都会被分配。
关于c - malloc 之后访问结构数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14515577/