c - malloc 之后访问结构数组的内容

标签 c arrays struct char malloc

我正在尝试将单词和每个单词的数量存储在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/

相关文章:

c - 关于缓冲区溢出

Jquery:将字段值保存到多维数组中

python - 将 Python 数组导出到 Matlab

swift - 使用 Swift 从 NSData 中获取数据

c - 结构、typedef 和 malloc、calloc

c - 在 malloc 中,为什么要使用 brk?为什么不直接使用 mmap?

c - C将如何解析这句话?

C 中引用其他结构的结构的构造函数

c - 结构内存分配错误

javascript - 转换数组并反转