使用C中的scanf函数获取数组的值 [英] getting values for an array using scanf function in C
问题描述
我有一个函数定义,该函数定义使用scanf通过用户获取数组的值。这就是我所拥有的
I have a function definition that gets values for an array trough the user using 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]);
}
}
当我尝试打印数组时出现错误在scanf的一行上说格式指定类型为'float *',但参数的类型为'int'。我尝试将%f更改为%d,以便scanf和printf具有相同的占位符
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
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?
推荐答案
函数 scanf()
的位置从 stdin
到您告诉它的任何地方的输入。您在 scanf()
中提供的第二个参数不是指示用户输入应该去哪里的指针- arr [i]
是一个整数。格式化后的第二个参数必须是指针。
The function scanf()
places the input from stdin
to wherever you tell it. 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. The second argument after formatting needs to be a pointer.
因此,您需要以下内容:
So, you want something along the lines of the following:
scanf("%d", (arr+i));
或
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.
第二种情况是首先提供数组中第ith个元素的值, arr [i]
,然后&号在内存中给出该元素所在位置的地址-因此是一个指针。
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.
这篇关于使用C中的scanf函数获取数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!