通过以下代码,我得到了一个非常奇怪的结果。为什么最后一个元素的值会覆盖所有以前的数组元素?我怀疑还有比眼前的问题更大的问题。
#include <stdio.h>
main()
{
int i, cases;
char num[1000000];
scanf("%d", &cases);
char* array[cases];
//store inputs in array
for(i=0; i<cases; i++)
{
scanf("%s", &num);
array[i] = #
}
//print out array items and their memory addresses
for(i=0; i<cases; i++)
{
printf("%d %s\n", i, array[i]); //print (array index) (array value)
printf("%d %p\n", i, &array[i]); //print (array index) (array address)
}
}
Inputs:
3 <-- number of lines to follow
0 <-- put in array[0]
1 <-- put in array[1]
2 <-- put in array[2]
Outputs
0 3 <-- why is this being overwritten with the last element?
0 0013BCD0
1 3 <-- why is this being overwritten with the last element?
1 0013BCD4
2 3
2 0013BCD8
最佳答案
这里的结果是 array[i] = #
行,您将 array[i]
元素的值设置为 的地址>num
数组;由于 array
是一个字符数组,我怀疑它正在截断您的 num
数组地址,而低位字节恰好是 3。
但是。也就是说,您的 char num[1000000] 是可怕的形式,您根本不应该这样做。在堆上分配,并选择一个较小的数字,看在上帝的份上。此外, scanf("%s", &num) 实际上不会给你你想要的。这是一个提示;使用 getc() 循环读取数字;这避免了需要为 scanf() 进行数组的任何预分配。
关于c - 数组成员被最后一个元素覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/895628/