gpt4 book ai didi

c - 字符串数组相互覆盖?

转载 作者:太空宇宙 更新时间:2023-11-04 05:21:40 25 4
gpt4 key购买 nike

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

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] );


}

谢谢

最佳答案

每次while循环都需要为newEntry分配新的内存。您当前多次存储指向单个 newEntry 缓冲区的指针。

你说查过地址,具体查的是什么地址?

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

关于c - 字符串数组相互覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3972453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com