0
votes

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]);
    }
}

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?

2
thank you it works - JDK
@JDK Doesn't every scanf tutorial show how to do this correctly? - Barmar
You cannot possibly get the same error if you do that change you say. - klutt
BDW which compiler did you use? And did you input all your elements correctly? - LinuxStuff

2 Answers

1
votes

it looks like you need to add & before your arr[i]:

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

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));

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.