简体   繁体   中英

why won't this program give me the output i want?

I've written this simple code so I can see what's wrong with a more complex program that I have written.

#include<stdio.h>
int main()
{
    int n = 0, i = 1, a = 0;
    scanf("%d", &n);
    while (i <= n)
    {
        scanf(" %d", &a);
        printf("%d", &a);
        i++;
    }
}

but when I run the program it goes like this: 4 1 6487620 what's wrong with it?

In your code

 printf("%d", &a);

should be

printf("%d", a); // don;t print address....

FWIW, passing an address (a pointer type) as an argument to %d is a mismatch and invokes undefined behavior .

When you use printf("%d", &a);

this means that it will print the address of a

and to print the value of a you have to wright

printf("%d", a);

and after making the changes compile the program and try to rerun :)

You pass the address of a instead of its value to printf . You should also output a linefeed to separate the numbers:

printf("%d\n", a);

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