【问题标题】:C char** array only stores last most recently assigned stringC char** 数组仅存储最近分配的字符串
【发布时间】:2017-11-05 20:33:00
【问题描述】:

我正在尝试将字典存储到一个名为 spellingList 的大数组中。 fgets() 循环似乎工作正常,但是当检查存储在 spellingList 中的内容时,它显示数组的每个元素都是 zygote(字典中的最后一个单词)。

给定一个名为 dictionary 的文件,其中包含一长串单词,格式如下:

字典

barbecue
barbecue's
barbecued
barbecues
barbecuing
barbed
.
.
.
zwieback's
zygote
zygote's
zygotes

代码

int i = 0;
int j;
char *pos;

    /* Open Dictionary */
FILE *dic;
dic = fopen("dictionary", "r");

    /* Malloc Storage Array */
char **spellingList;
spellingList = malloc (sizeof(char*) * 100000);

if (spellingList == NULL){   // if malloc fails
  printf("%s\n", "Malloc failure");
  exit(0);
}

    /* load dictionary into array */
while (1){
  if (fgets (word, 50, dic) != NULL){         

    if ((pos=strchr(word, '\n')) != NULL){ // replace ending '\n' with a '\0'
      *pos = '\0';
    }
    printf("%d  %s\n", i, word );  // looks as expected
    spellingList[i] = word;
    i++;
  }
  else {
    break;
  }
}  fclose(dic);  // close fd to dictionary

for (j =0; j < 100; j++){  // output
   printf("%d  %s\n", j, spellingList[j]);
}

输出

.
.
.
90  zygotes
91  zygotes
92  zygotes
93  zygotes
94  zygotes
95  zygotes
96  zygotes
97  zygotes
98  zygotes
99  zygotes

【问题讨论】:

  • 我假设word 是一个数组?然后让spellinglist 中的所有指针指向指向同一个数组。
  • 您一遍又一遍地存储同一个指针 (word)。
  • char ** 不是数组!指针不能是数组。

标签: c arrays initialization


【解决方案1】:

因为您正在存储指针值,然后更改指针指向的数据将有效地更改数组中的所有值。

您必须复制数据以避免这种情况,一种方法是

spellingList[i] = strdup(word);

也就是说,赋值word不会复制数据,它只是让spellingList[i]指向word的内存位置,所以所有元素都指向同一个位置。

您必须阅读有关指针的更多信息。

【讨论】:

  • @LTNoodles 不要忘记所有free(spellingList[i]) 和free(spellingList) 在其使用寿命结束时。
猜你喜欢
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 2012-05-03
  • 1970-01-01
  • 2015-04-25
  • 2022-10-06
  • 2012-07-12
相关资源
最近更新 更多