C101:从用户输入填充数组的最佳方法是什么?
我很难理解,因此很难在C中手动管理数组和索引。这是我的两种经典方法,但是当达到条件时它们会不断循环,因此它们似乎不起作用:
#include<stdio.h> #define MAX 255 int main(){ int arr[MAX]={0}; int idx=0; /* Approach #1 */ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); while(arr[idx-1] != -1 && idx < MAX){ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); idx++; } /* Approach #2 */ do{ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); idx++; }while(arr[idx-1] != -1 && idx < MAX); // Main func continues here. }
任何建议将不胜感激!
更新:
现在可以了!非常感谢你们大家如此迅速的反应。这绝对是一个很棒的社区,对我有很大帮助。
解决方案
arr[idx] <= MAX
应该
idx <= MAX
C数组从0开始计数。
如果分配大小为MAX的数组,则访问MAX的元素将是错误的。
将循环更改为;
int arr[MAX]; for ( .... && idx < MAX )
arr[idx] <= MAX
应该
idx < MAX
除非我们要检查项目而不是索引。
我们还总是在检查" next"元素是否为-1(arr [idx]!= -1),因为在检查添加值之前要递增idx。
所以如果你有
arr[idx-1] != -1
你会没事的。
在第一个while循环中,
arr[idx] <= MAX
行应阅读
idx <= MAX
在第二个循环中,我们要在测试结束之前增加idx
} while ((arr[idx-1] != -1) && (idx-1 <= MAX));
我也倾向于在所有内部条件中加上括号,以便绝对确定优先顺序是正确的(因此,在上面加上了括号)。
while(arr[idx] != -1 && idx <= MAX){ // Fixed by sklivvz printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); idx++; }
首先,我们应该检查索引variabel idx是否小于MAX(不小于或者等于)。如果索引等于MAX,那么我们将超出范围。 MAX = 10的数组的索引值为0到9(包括9),但不包括10.
其次,将第一个元素添加到arr [0],将索引从0增加到1,然后跳回到while条件,并检查arr [1] == -1,不是。因此,请检查arr [idx-1]!= -1. 但是请注意,第一次进入while循环时,实际上将检查arr [-1]!= -1,这也超出了范围。 ;)因此,我们需要弄清楚如何解决这一问题。
我会喜欢这样的东西。
我们不必担心数组边界和其他令人困惑的条件。
int cnt = MAX; // how many elements in the array, in this case MAX int * p = &arr[0]; // p is a pointer to an integer and is initialize to the address of the first // element of the array. So now *p is the same as arr[0] and p is same as &arr[0] // iterate over all elements. stop when cnt == 0 while (cnt) { // do somthing scanf("%d", *p); // remember that *p is same as arr[some index] if (*p == -1) // inspect element to see what user entered break; cnt --; // loop counter p++; // incrementing p to point to next element in the array }
到罗马M:
首先,问这个问题的人刚刚开始编程课程,并且可能尚未了解指针。其次,我们现在同时处理一个计数器和一个指针。我不确定我会看到这样做的好处,而不是使用像这样的索引:
for(idx = 0; idx <MAX; ++ idx){
scanf("%d", &arr[idx]); if(arr[idx] == -1) break;
}
使用for循环,我们可以消除对凌乱的idx-1检查代码的需要:
/* Approach #3*/ int i; int value; for (i = 0; i < MAX; ++i) { printf("Enter elements, -1 to finish:\n"); scanf("%d", &value); if (value == -1) break; arr[i] = value; }