我的 C 程序由一个名为“test_var”的数组组成。它有另一个整数数组“arr_int”,由一组整数组成。我的代码看起来像这样:
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
int State(var);
int main()
{
int arr_int[3] ={1000, 1001, 1002, 1003};
int var;
int *test_var[4]={0};
State(var)
{
int i;
for(i=0; i<4; i++){
test_var[i] = arr_int[i];
i++;
}
return test_var[var];
}
printf("Enter a number between 0 and 3\n");
scanf("%d",&var);
State(var);
printf ("The array structure is %d", test_var[var]);
return 0;
}
但是现在,当我尝试打印用户输入 var=0 而不是整个数组(1000)的返回值数组 test_var 时,我只得到 0。我在这里做错了什么?有人可以告诉我吗?我是否以错误的方式取消引用数组?
编辑:没有拼写错误的代码:
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
int State(var);
int main()
{
int *arr_int[3] ={1000, 1001, 1002, 1003};
int var;
int *test_var[4]={0};
State(var)
{
int i;
for(i=0; i<4; i++){
test_var[i] = arr_int[i];
i++;
}
return test_var[var];
}
printf("Enter a number between 0 and 3\n");
scanf("%d",&var);
State(var);
printf ("The array structure is %d", test_var[var]);
return 0;
}
最佳答案
就你而言,
声明
test_var[i] = arr_int[i];
是错误的。
test_var[i]
的类型为int *
,而arr_int[i]
的类型为int
,并且它们并不真正兼容。引用标准,第 §6.3.2.3 章An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
然后,您正在使用另一个语句,例如
printf ("The array structure is %d", test_var[var]);
%d
需要一个int
参数,但您提供的是一个int *
。纯undefined behaviour .之后,
int State(var)
依赖于 default-to-int
的旧概念,该概念已被从C99
开始无效。在 3 个元素的数组中,您提供 4 成员初始值设定项列表。无用且令人困惑。
也就是说,FWIW,您使用的是嵌套函数,它也不是标准 C 的一部分。 It is supported as a GCC extension .
<小时/>编辑:
根据评论,即使您的 arr_int
是 int *
类型的数组,初始化器也不会提供看似有效的有效要取消引用的指针的值。这意味着,您无法访问这些指针指向的内存,它们很可能位于进程分配的内存区域之外,因此无效。
尽管如此,对于前面提到的第 2 点,代码是 UB。
关于c - 为什么我的程序显示数组地址而不是其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812329/