简体   繁体   中英

compiler can not execute last two printf functions

#include<stdio.h>

int main()
{
    int a[100], i, n, sum=0;
    printf("How many number:");
    scanf("%d", &n);
    for ( i = 0; i < n; i++)
    {
        scanf("%d", a[i]);
        sum = sum + a[i];
    }
    printf("Sum is: %d\n", sum);
    printf("Average is %0.2f", (float)sum/n);
    return 0;
}

What's the problem with my code? last two printf functions can not execute by the compiler. There any problem with my code?

The scanf function needs to be passed a pointer to the data you want to read into.

 for ( i = 0; i < n; i++) { scanf("%d", a[i]); sum = sum + a[i]; }

a[i] passes an int rather than a pointer to int . Now, as pointers are just numbers, and you've provided it with one, your code will compile, but your compiler should warn you about this if you compile with warnings on.

Doing this will definitely yield undefined behavior.

Instead you'll want to pass the address of a[1] :

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

You may also wish to check the return from scanf to ensure it actually is reading in what you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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