我正在尝试将扫描值保存在数组中。听起来很简单,但这里是我遇到问题的地方: 以下是报告为其他成员的编辑代码:
#include <stdio.h>
int main()
{
int length;
scanf("%d ", &length);
int array[length]; // Added the missing ;
for(int i=0; i<length; i++) // Loop from 0
{
scanf("%d ", &array[i]); // Used & properly here.
}
for(int j=0; j<length; j++) // Loop from 0
{
printf("%d\n", array[j]);
}
return 0;
}
我现在遇到的问题是该程序仍然需要运行11个数字。所以,如果我输入
10
1 2 3 4 5 6 7 8 9 10
在我输入另一个号码之前没有任何事情发生。
编辑:最后想出了为什么它等待第11个数字:显然它等待获得另一个空格,所以我只用scanf(“%d)替换scanf(”%d“)并且它正在工作。答案 0 :(得分:2)
&array[i]
传递给scanf。答案 1 :(得分:1)
参见内联评论。
#include <stdio.h>
int main()
{
int length;
scanf("%d ", &length); // You used & properly here!
int array[length] // You forgot a semi-colon here!
for(int i=1; i<length; i++) // Loop: for(int i=0; i<length; ++i)
{
scanf("%d ", array[i]); // Why didn't you use & here???
}
for(int j=1; j<length; j++) // Loop: for(int j=0; j<length; ++j)
{
printf("%d\n", array[j]);
}
return 0;
}
这是程序的IDEOne link,它表明它与length=10
和10个数字作为输入正常工作
完全更正的代码是:
#include <stdio.h>
int main()
{
int length;
scanf("%d ", &length);
int array[length]; // Added the missing ;
for(int i=0; i<length; i++) // Loop from 0
{
scanf("%d ", &array[i]); // Used & properly here.
}
for(int j=0; j<length; j++) // Loop from 0
{
printf("%d\n", array[j]);
}
return 0;
}
<强> 输入 强>
10
1 2 3 4 5 6 7 8 9 10
答案 2 :(得分:1)
C ++ / C数组是从0开始的索引,如果你必须访问数组的第一个元素,你必须使用0索引而不是1,考虑这个大小为5的数组(即其中的五个元素{23} {19} {6} {70} {9})
请注意,数组的0位置(索引)未初始化。现在请注意这里对您的代码的解释。
int main()
{
int length = 0; //Please consider initializing it
scanf("%d ", &length); //User input '10'
//Now you have an array of size 10 (10 consecutive memory locations to store int
int array[length];
//Now consider the memory locations somewhat like this with raw values say 'xx'
//0:[xx], 1:[xx], 2:[xx], 3:[xx], 4:[xx], 5:[xx], 6:[xx], 7:[xx], 8:[xx], 9:[xx]
for (int i = 1; i < length; i++)
{
scanf("%d ", &array[i]); //Notice the fix here '&array[i] is used.
}
//After providing some data the memory view is somewhat like this,
//notice the loop started from position/index 1 in array and went
//upto 9th position
//0:[xx], 1:[11], 2:[22], 3:[33], 4:[44], 5:[55], 6:[66], 7:[77], 8:[88], 9:[99]
for (int j = 1; j < length; j++)
{
printf("%d\n", array[j]);
}
//The above loop started from position 1 (not 0) and loop through 9 indexes and printed this
//11
//22
//33
//44
//55
//66
//77
//88
//99
return 0;
}
这是固定代码,请注意从&#39; 0&#39;开始的for循环。基础指数。
int main()
{
int length = 0;
scanf("%d ", &length);
int array[SIZE];
for (int i = 0; i < length; i++)
{
scanf("%d ", &array[i]); //Notice the fix here '&array[i] is used.
}
for (int j = 0; j < length; j++)
{
printf("%d\n", array[j]);
}
return 0;
}
希望它能帮助您理解如何在C ++ / C中处理数组