[问题]scanf读进variable length array问题

楼主: codefarmer (自信)   2017-09-14 00:02:50
开发平台(Platform): Win7
编译器: GCC
问题(Question):
程式利用scanf()读档案至int s[num], int t[num],
问题发生在写入 t[4] 时, s[0]的值跟着被覆蓋,
利用printf印出 t[4] 跟 s[0]的 address 发现两者相同...
想请问大神们, 明明是两个不同的ARRAY,
为何compiler 将两者的element 放在相同位址?
是否是小弟有疏忽,才造成这样的情形呢?
喂入的资料(Input):
5
1 2 4 6 8
3 5 7 9 10
预期的正确结果(Expected Output):
num = 5
t[i] = 3; s[0] = 1
t[i] = 5; s[0] = 1
t[i] = 7; s[0] = 1
t[i] = 9; s[0] = 1
t[i] = 10; s[0] = 1
错误结果(Wrong Output):
num = 5
t[i] = 3; s[0] = 1
t[i] = 5; s[0] = 1
t[i] = 7; s[0] = 1
t[i] = 9; s[0] = 1
t[i] = 10; s[0] = 10
&s[0] = 0xffffcb80, &t[4] = 0xffffcb80
程式码(Code):
#include <stdio.h>
int main(int argc, char const *argv[])
{
const int num;
int s[num];
int t[num];
scanf("%d", &num);
printf("num = %d\n", num);
for (int i = 0; i < num; ++i)
scanf("%d", &s[i]);
for (int i = 0; i < num; ++i) {
scanf("%d", &t[i]);
printf("t[i] = %d; s[0] = %d\n", t[i], s[0]);
}
printf("&s[0] = %p, &t[4] = %p\n", &s[0], &t[4]);
return 0;
}
作者: ilikekotomi (Young)   2017-09-14 00:13:00
num的值是在定义之后给的 这样s和t的阵列大小不是5
作者: jerryh001   2017-09-14 00:13:00
宣告阵列的时候 num还是未知数
作者: windada2 (如此重要)   2017-09-15 01:17:00
阵列设置初始大小是不能用变量的呦
作者: LPH66 (-6.2598534e+18f)   2017-09-15 01:33:00
C99 可以, gcc 在 C90 模式和 C++ 是以 extension 支援

Links booklink

Contact Us: admin [ a t ] ucptt.com