我正在创建一个函数,将一个单词列表转换为一个数组供其他函数使用,但不知怎的,我正在覆盖以前的单词.我检查内存地址'并且它们看起来不同,但是当我重新检查一次我完成导入单词后,它们都是一样的.
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] );
}
Run Code Online (Sandbox Code Playgroud)
谢谢
您需要newEntry通过while循环每次分配新内存.您当前正在newEntry多次存储指向单个缓冲区的指针.
当您说您已经检查了地址时,您具体检查了哪个地址?
实际上,这里技术上可能发生的事情是,在每次迭代while循环后,您将存储对超出范围的变量的引用.由于它超出了范围,因此编译器可以自由地重用它为循环的下一次迭代所做的堆栈内存.
| 归档时间: |
|
| 查看次数: |
1790 次 |
| 最近记录: |