为什么“1”存储在所有数组索引位置?

时间:2015-11-08 19:57:39

标签: c arrays for-loop printf

我正在学习和练习C.抛开输出格式。我不明白为什么所有数组元素都输出“1”,或者数字来自哪里。

即使我输入5“5”,输出仍然总是“1”。

#define LIMIT 5
#include <stdio.h>
#include<stdlib.h>
void getNums();

int main() {
    getNums();
    return 0;
}

void getNums() {
    int newRay[LIMIT];
    for(int i = 0; i < 5; i++) {
        int element;
        int result = scanf("%d", &element); 
        newRay[i] = result;
        printf("%d", newRay[i]);
    }
}

4 个答案:

答案 0 :(得分:2)

result存储scanf的返回值,即提供给scanf的格式字符串中的匹配数。您真正想要的是读取的值,存储在element

        newRay[i] = element;

注意:

  • 更好地始终使用LIMIT。你的程序可能只是“快速”而且“很脏”#34;但是你应该替换5循环中的for

答案 1 :(得分:2)

scanf返回成功分配的输入数。在您的情况下,如果element的分配成功,则返回1.

您可能打算使用:

    newRay[i] = element;

你应该做的是:

    int result = scanf("%d", &element);
    if ( result == 1 )
    {
       newRay[i] = element;
    }
    else
    {
       // Unable to read the input
       // Deal with error.
    }

答案 2 :(得分:1)

您正在为数组元素指定scanf的返回值。 scanf返回分配的输入项数。

scanf("%d", &element);中,只分配了一个输入项,因此它将返回1

更改

int result = scanf("%d", &element); 
newRay[i] = result;  

scanf("%d", &element);
newRay[i] =  element

答案 3 :(得分:0)

你得到“1”的原因是因为你只捕获了scanf函数的返回值。您输入的值由scanf返回,但它被复制到元素(您通过引用它来使用它 - &amp; element)。不需要结果变量。

void getNums(){ int newRay[LIMIT]; int element; for(int i=0; i<5;i++){ scanf("%d",&element); newRay[i] = element; printf("%d", newRay[i]); } }