我很难理解并因此在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

除非您检查项目而不是索引。

您也一直在查看<!>“下一个<!>”; -1的元素(arr [idx]!= -1)因为您在检查添加值之前递增了idx。

所以,如果你有

arr[idx-1] != -1
你会没事的。

其他提示

arr[idx] <= MAX

应该是

idx <= MAX
while(arr[idx] != -1 && idx <= MAX){ // Fixed by sklivvz
    printf("Enter elements, -1 to finish:\n");
    scanf("%d", &arr[idx]);
    idx++;        
}

首先,您应该检查索引变量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,这也是超出范围的。 ;)所以你需要弄清楚如何解决这个问题。

到罗马M:

首先,问这个问题的人刚刚开始编程课程,可能还没有学过指针。其次,你现在处理一个计数器和一个指针。我不确定与使用这样的索引相比,我看到了这样做的好处:

for(idx = 0; idx <!> lt; 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;
}

C数组从0开始计数。

如果分配一个大小为MAX的数组,则访问MAX处的元素将是一个错误。 将循环更改为;

int arr[MAX];
for ( .... && idx < MAX )

在你的第一个while循环中,

arr[idx] <= MAX

行应该读

idx <= MAX

在你的第二个循环中,你在测试之前增加idx - 它应该以

结束
} while ((arr[idx-1] != -1) && (idx-1 <= MAX));

我也倾向于将所有内部条件括起来,只是为了绝对确定优先级是正确的(因此上面的额外括号)。

我会选择这样的东西。

您不必担心数组边界和其他令人困惑的情况。

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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top