简体   繁体   English

在 C 中使用 scanf function 获取数组的值

[英]getting values for an array using scanf function in C

I have a function definition that gets values for an array trough the user using scanf.我有一个 function 定义,它通过用户使用 scanf 获取数组的值。 This is what i have这就是我所拥有的

void readInArray(int *arr, int size) {
    int i;
    printf("Enter your list of numbers: ");
    for (i = 0; i < size; i++) {
        scanf("%f", arr[i]);
        printf("%d\n", arr[i]);
    }
}

when i try to print the array i get an error at the line with scanf saying "format specifies type 'float *' but the argument has type 'int'".I tried changing %f to %d so that both scanf and printf have the same place holder当我尝试打印数组时,在 scanf 行中出现错误,提示“格式指定类型为‘float *’,但参数的类型为‘int’”。我尝试将 %f 更改为 %d,以便 scanf 和 printf 都有相同的占位符

void readInArray(int *arr, int size) {
    int i;
    printf("Enter your list of numbers: ");
    for (i = 0; i < size; i++) {
        scanf("%d", arr[i]);
        printf("%d\n", arr[i]);
    }
}

but i still get the same error.但我仍然遇到同样的错误。 How can i fix this?我怎样才能解决这个问题?

The function scanf() places the input from stdin to wherever you tell it. 函数scanf()将来自stdin放到您告诉它的任何位置。 The second argument you are providing in scanf() is not a pointer directing where the input from the user should go -- arr[i] is an integer. 您在scanf()中提供的第二个参数不是指示用户输入应该转到何处的指针arr[i]是整数。 The second argument after formatting needs to be a pointer. 格式化后的第二个参数需要是一个指针。

So, you want something along the lines of the following: 因此,您需要遵循以下原则:

scanf("%d", (arr+i));

or 要么

scanf("%d", &arr[i]);

For the first case, passing an array as an argument is the same as passing a pointer to the first element in the contiguous block of memory the array holds. 对于第一种情况,将数组作为参数传递与将指针传递到数组所保存的连续内存块中的第一个元素相同。 Incrementing by an integer will take you to the next element. 整数递增将使您进入下一个元素。

The second case is first providing the value of the ith element in the array, arr[i] , and then the ampersand gives the address in memory of where that element is located -- so a pointer. 第二种情况是首先提供数组中第ith个元素的值arr[i] ,然后&符给出该元素所在的内存位置的地址-因此是一个指针。

看来您需要在&r [i]之前添加&:

scanf("%d", &arr[i]);

Writing the code as follows, it will work写代码如下,就可以了

int i, *marks;

for(i=0;i<5;i++){
    printf("\nenter marks[%d] : ",i);
    scanf("%d",&marks[i]);
    printf("\nenter marks[%d] finished : ",i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM