c - 为什么我的程序接受一个整数太多而输入一个太少



我想了解为什么当我将 SIZE 定义为 2 时,程序允许我输入 3 个整数。当它返回数组时,它只返回两个数字,而不是我输入的三个数字。感谢您的帮助。

//C How to Program Exercises 2.23
#include <stdio.h>
#include <conio.h>
#define SIZE 2
int main (void){
    int myArray[SIZE];
    int count;
    printf("Please enter 5 integersn");
    for (count=1;count<=SIZE;count++){
        scanf("%dn",&myArray[count]);
    }
    for (count=1;count<=SIZE;count++){
        printf("The values of myArray are %dn",myArray[count]);
    }
    getch();
    return 0;
}

你的循环应该是

for (count=0;count<SIZE;count++)

数组索引0基于 C 语言。

由于您在scanf()调用中有一个空格聊天者(n),它会等待您输入非空格字符来完成每次调用。删除n

   for (count=0;count<SIZE;count++){
    scanf("%d",&myArray[count]);
}

C 数组的索引是从 0 开始的,而不是从 1 开始索引的。 C 不会自动对数组访问执行边界检查,事实上,您的代码格式正确。 但是,它的运行时行为是未定义的,因为它使用数组元素表达式在该数组的边界之外写入,并且单独地,因为它使用数组元素表达式读取该数组边界之外。

由于程序在每次运行时肯定会表现出未定义的行为,因此绝对不能说它应该做什么。 如果在实践中观察到输入循环迭代三次,那么可能的解释是第二次迭代覆盖了count变量的值。 给定变量的声明顺序,这是未定义行为的合理表现。

另一方面,输出循环精确地迭代了您告诉它的次数:一次使用 count == 1 ,一次使用 count == 2 。 考虑到程序执行的一般未定义性,这绝不是保证的,但这是我能想到的最不令人惊讶的行为。

为什么程序允许我输入 3 个整数

此循环正好运行 2 次:

for (count=1;count<=SIZE;count++){
        scanf("%dn",&myArray[count]);
    }

但是正如您在scanf()中使用n一样,此scanf()会等到您提供任何空格。

Proper Input code:

for (count=0;count<SIZE;count++){
        scanf("%d",&myArray[count]);
    }

当它返回数组时,它只返回两个数字

您的

原始输出代码正确打印第一个数字,但您的第二个数字是垃圾值。

Proper Output Code:

for (count=0;count<SIZE;count++){
        printf("The values of myArray are %dn",myArray[count]);
    }

所以完整代码是这样的:

//C How to Program Exercises 2.23
#include <stdio.h>
#include <conio.h>
#define SIZE 2
int main (void){
    int myArray[SIZE];
    int count;
    printf("Please enter 5 integersn");
    for (count=0;count<SIZE;count++){
        scanf("%d",&myArray[count]);
    }
    for (count=0;count<SIZE;count++){
        printf("The values of myArray are %dn",myArray[count]);
    }
    getch();
    return 0;
}

最新更新