Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 字符串数组是否相互覆盖?_C_Arrays - Fatal编程技术网

C 字符串数组是否相互覆盖?

C 字符串数组是否相互覆盖?,c,arrays,C,Arrays,我正在制作一个函数,将单词列表转换为一个数组,供其他函数使用,但不知何故,我覆盖了前面的单词。我检查了内存地址,它们看起来不一样,但当我导入完单词后重新检查时,它们都是一样的 static char **array; //takes the name of a data file and reads it into an array static void InitDictionary(char *fileName){ //slide 36, chap 3 FILE *file;

我正在制作一个函数,将单词列表转换为一个数组,供其他函数使用,但不知何故,我覆盖了前面的单词。我检查了内存地址,它们看起来不一样,但当我导入完单词后重新检查时,它们都是一样的

static char **array;

//takes the name of a data file and reads it into an array
static void InitDictionary(char *fileName){
  //slide 36, chap 3
  FILE *file;
  int count,i;
  char dummy[30];
  file = fopen(fileName, "r");

  while( fscanf(file, "%s", dummy) == 1 ){//counting at first
    count++;
  }
  fclose(file);

  array = (char**) malloc(count * sizeof(char*) );
  count = 0;
  file = fopen(fileName, "r");
    while( fscanf(file, "%s", dummy) == 1 ){//now putting values in array
      char newEntry[30];
      strcpy(newEntry,dummy);
      array[count] = newEntry;
      printf("%d - %s : %p \n",count, array[count], &array[count]);

      count++;
    }
  fclose(file);

  for(i=0;i<count;i++)
    printf("%d - %s : %p\n",i, array[i], &array[count] );


}
静态字符**数组;
//获取数据文件的名称并将其读入数组
静态void InitDictionary(char*文件名){
//幻灯片36,第3章
文件*文件;
int计数,i;
伪字符[30];
file=fopen(文件名为“r”);
而(fscanf(文件“%s”,dummy)==1){//开始计数
计数++;
}
fclose(文件);
数组=(char**)malloc(count*sizeof(char*);
计数=0;
file=fopen(文件名为“r”);
虽然(fscanf(文件“%s”,dummy)==1){//现在正在数组中放入值
char newEntry[30];
strcpy(新条目,虚拟);
数组[计数]=新条目;
printf(“%d-%s:%p\n”、count、array[count]、&array[count]);
计数++;
}
fclose(文件);

对于(i=0;i您需要通过while循环每次为
newEntry
分配新内存。您当前多次存储指向单个
newEntry
缓冲区的指针

当你说你已经检查了地址,你具体检查了哪个地址


实际上,从技术上讲,这里可能发生的事情是,在while循环的每次迭代之后,您存储了对超出范围的变量的引用。由于它超出了范围,编译器就可以自由地重用堆栈内存,这是它在循环的下一次迭代中所做的。

我看到的一个问题是,count没有初始化您正在malloc中使用它。

user470379是正确的,您没有为每个新词分配空间。一个可能的修复方法是替换三行:

char newEntry[30];
strcpy(newEntry,dummy);
array[count] = newEntry;


只需确保在完成时释放内存——为必须释放的新副本释放strdup mallocs空间。@user470379-确切地说,执行单个strdup是一项非常复杂的资源管理。将整个文件读入一个分配的内存块,然后索引和NUL在适当的位置终止每个字,可能会更简单、更快这个洞以后可以立即释放。
array[count] = strdup(dummy);