【问题标题】:access contents of an array of structs after malloc在 malloc 之后访问结构数组的内容
【发布时间】: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


【解决方案1】:
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 );

每个struct word 中的字符串的内存是在您执行malloc 时分配的。

【讨论】:

  • 这是唯一正确的答案。数组在 C 中不可赋值。您必须使用 strcpy 或(首选)strncpy,如 @radical7 所示。
【解决方案2】:

首先,最后一行应该是

struct word *words = malloc(wordCount * sizeof(word));

您需要单词结构的大小,而不是您在这一行声明的变量...

除此之外,您需要做的是将words 中的每个结构初始化为一些合理的默认值,如下所示:

words[0].num = 0; // or any values you please, really
words[0].str[0] = '\0';

【讨论】:

  • 很好地抓住了sizeof 的错误。
【解决方案3】:

您可以将words 作为指针或数组访问:

words[0]

是第一个结构体。

words[0].str

是第一个词。并遍历所有单词:

for (int iWord = 0; iWord < wordCount; ++iWord)
{
    // words[iWord] is the current word
    printf("%s", words[iWord].str);
}

如果你更喜欢指针(在这种情况下我不喜欢),那么:

(words+5)->str

这是第 6 个单词吗(记住我们从 0 开始编号)。但你可能会使用这样的指针:

for (struct word *pWord = words; pWord < words+wordCount; ++pWord)
{
    // pWord is the current word
    printf("%s", pWord->str);
}

【讨论】:

  • 这就是我的想法,但我得到了这个编译错误:从类型'分配给类型'char [(unsigned int)MAX_WORD_LENGTH]'时不兼容的类型'
  • 哪一行出现错误?其余的错误是什么?在 C 中你不分配字符串,你必须复制它们strcpy(words[iWord].str, curWord);
猜你喜欢
  • 2020-12-14
  • 2015-07-30
  • 1970-01-01
  • 2022-01-07
  • 2014-03-10
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多