【问题标题】:Do I need to initialize the values of a structure before I use them?我需要在使用之前初始化结构的值吗?
【发布时间】: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


【解决方案1】:

如果使用malloc,则需要初始化数组(例如,使用memset)。如果你使用calloc,数组会为你初始化为0。

一旦数组被初始化,你可以在它上面使用strcmp,因为将它设置为0会使所有的单词都是零长度(空)的字符串。在初始化之前,千万不要使用strcmp

(我假设奇怪的 char[50] varname 而不是 char varname[50] 是您的 SO 问题中的拼写错误,否则这将无法编译。我也忽略了 fscanfstrcpy 中的缓冲区溢出......好吧,从技术上讲,我想我不是。而且缺乏错误处理。)

【讨论】:

  • 好的,然后将其切换到 calloc() 。 fscanf 的缓冲区溢出是什么?
  • @MichaelSchilling:你假设的那个永远不会发生——一个超过 49 个字符的单词。您可以使用%49s 告诉fscanf 最大长度。
【解决方案2】:

嵌套的 for 循环应该使用 wordListIndex 作为边界条件,最后一个 if 块应该从内部 for 循环中取出。条件应该是

if (j == wordListIndex){
  strcpy(wordList[wordListIndex].word, inWord)
  wordListIndex++;
}

【讨论】:

  • 我刚刚意识到不应该在第二个 for 循环中,而应该在第二个循环中。立即修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多