Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

c - Program crashes when trying to read numbers with scanf

A message like this appears, when i run this code. Project.exe has stopped working

Some of my other code works, but this seems to throw me an error.

enter image description here

#include<stdio.h>
#include<conio.h>

void main()
{
    int n1, n2, sum;

    puts("first number");
    scanf("%d", n1);
    fflush(stdin);
    puts("second number");
    scanf("%d", n2);
    sum = n1 + n2;

    printf("%d + %d = %d", n1, n2, sum);

    getch();

}

I basically want to add two numbers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

scanf takes the address of the variable in which it stores the input value. You need to change your scanf calls to

scanf("%d", &n1);
scanf("%d", &n2);
//          ^ note the & operator

Also, note that it's undefined behaviour to call fflush on an input stream. So, fflush(stdin) is not correct. You need to manually read and discard extraneous input left over in the stdin stream.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...