Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting values for an array using scanf function in C

Tags:

arrays

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

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?

like image 649
JDK Avatar asked Nov 27 '25 23:11

JDK


2 Answers

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.

like image 117
rigby Avatar answered Nov 29 '25 14:11

rigby


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

scanf("%d", &arr[i]);
like image 23
Halina V Avatar answered Nov 29 '25 13:11

Halina V