这是我的代码
#include<stdio.h>
int main()
{
int n,a[n],op;
printf("Enter size of the arrayn");
scanf("%d",&n);
printf("Enter the array elementsn");
for(int i=0;i<n;i++)
{
scanf("%d",&a[n]);
}
printf("Select array element to display from 1 to %dn",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %dn",a[op-1]);
}
else
{
printf("Invalid Entryn");
}
return 0;
}
Enter size of the array
5
Enter the array elements
2
5
6
1
5
Select array element to display from 1 to 5
2
Element is 0
为什么会发生这种情况?I can 't figure this out
考虑您的代码:
int n,a[n],op;
由于此时n
的值未定义,由a[n]
创建的可变长度数组(VLA)将具有某种任意大小。C不会神奇地回到你请求n
值并调整数组大小的时间点:-)
您需要在之后创建VLA,您已经设置了n
的值,在main
的开头重新组织代码,如下所示:
int n,op;
printf("Enter size of the arrayn");
scanf("%d",&n);
int a[n];
这样,当您使用n
创建VLA时,它将是一个已知的值。
此外,您的scanf("%d",&a[n]);
是未定义的行为,因为n
将始终超出数组的末尾(其中包含索引0
到n-1
)。您应该使用i
作为索引。
还有其他逻辑问题,例如检查scanf
是否成功,并且您没有输入非正数,但这对于教育代码通常是可以的(假设这是什么)。当你作为一名程序员进行开发时,你会很自然地开始考虑这些可能性,并相应地加强你的代码。
通过示例,这是输入n
的更好方式,尽管您可以从非数字数据中恢复作为可选的额外选项(参见这里的C中漂亮的行输入解决方案):
int n = -1;
while (n < 1) {
printf("Enter array size (positive integer): ");
if (scanf("%d", &n) != 1) {
puts("nERROR: non-numeric");
exit(1);
}
}
scanf("%d",&a[n]);
应为scanf("%d",&a[i]);
错误在这部分代码中:
int n,a[n],op;
// int n is not defined as anything so it is a garbage value
// you specify the size of the array to be n
// which allocates an undefined size for the array
同样在你的第一个循环中,你重新分配了&a[n]
,这是未定义的,因为它超出了数组的大小,即使它是有效的,它也只会重新分配一个元素,它应该是&a[i]
。
修复它在定义数组'a'之前读取n的值。我所做的更改如下:
#include<stdio.h>
int main()
{
int n; // change
printf("Enter size of the arrayn");
scanf("%d",&n);
int a[n],op; // change
printf("Enter the array elementsn");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]); // change
}
printf("Select array element to display from 1 to %dn",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %dn",a[op-1]);
}
else
{
printf("Invalid Entryn");
}
return 0;
}