简体   繁体   中英

Why does cmd crash when I run this code?

I am an absolute beginner in C, and I wrote this code in codeblocks and built it, it had no errors. The program is, we input two integers and display, sum, subtraction, multiplication, and division of no1 and no2.

Here's the code :

#include <stdio.h>
int main ()
{
int no1,no2,sum,sub,multi,div;

printf("Enter your first number");
scanf("%d", &no1);
printf("Enter second number");
scanf("%d", no2);

sum=(no1+no2);
sub=(no1-no2);
multi=(no1*no2);
div= (no1/no2);

printf ("%d + %d = %d \n",no1,no2,sum);
printf ("%d - %d = %d \n",no1,no2,sub);
printf ("%d * %d = %d \n",no1,no2,multi);
printf ("%d / %d = %d \n",no1,no2,div);

return 0 ;
}

I got 0 errors but when I ran it, cmd opens, and then I input values for no1 and no2 then the program crashes and gives the message windows will look into the issue.

仔细查看以下代码段: scanf("%d", no2);

Say you declare a variable named foo.

int foo;

This variable occupies some memory. It occupies four bytes of memory (because an int is four bytes wide).

Now let's declare another variable.

int *foo_ptr = &foo;

foo_ptr is declared as a pointer to int. We have initialized it to point to the foo variable.

As I said, foo occupies some memory. Its location in memory is called its address. The char '&' is the “address-of" operator.

This operator returns the address of an variable. In our case foo, thus foo_ptr now point to the address memory of the foo variable.

Think of every variable as a box. foo is a box that is sizeof(int) bytes in size. The location of this box is its address. When you access the address, you actually access the contents of the box it points to.

盒子

You missed '&' here...

   printf("Enter second number");
    scanf("%d", &no2);

您忘记在第二个scanf处加上“&” :)

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