3

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?

3
  • 1
    @JDK Doesn't every scanf tutorial show how to do this correctly? Commented Jun 27, 2017 at 20:29
  • You cannot possibly get the same error if you do that change you say. Commented Jun 27, 2017 at 20:55
  • BDW which compiler did you use? And did you input all your elements correctly? Commented Jun 28, 2017 at 5:46

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

1 Comment

Not necessary with arrays.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.