Crash after reading value with scanf

5

First, I'm "noob" in programming. I started college today, and the subject was already rolling (third call has its consequences = P). The code is simple, the third one I created, however, after compiling and writing a value, CMD stops working.

The code itself is:

#include <stdio.h>
#include <windows.h>
int main (void) 
{
    int sal, novo_sal;
    printf ("Entre com sal");
    scanf ("%d, &sal");
    if (sal >= 1000) {
        novo_sal = 1.1 * sal;
        printf ("%d", novo_sal);
    }
    else { 
        novo_sal = 1.2 * sal;
        printf ("%d", novo_sal);
    }
}

My question is: Is there something wrong with the code, or with the compiler?

    
asked by anonymous 24.02.2014 / 23:14

3 answers

7

I suppose you mean it

scanf ("%d", &sal);

instead of

scanf ("%d, &sal");

The first one says, "Read a number and put it in the variable sal ".

The second says: "Read a number followed by ", &sal" and put that number in an unspecified place in memory".

Writing in 'random' pieces of memory will usually cause you to crash by writing in an area you could not write.

Compiling this code with GCC, I have the following diagnosis:

a.c: In function ‘main’:
a.c:7:5: warning: format ‘%d’ expects a matching ‘int *’ argument [-Wformat=]
     scanf ("%d, &sal");
     ^

Always pay attention to any alert your compiler gives you. And preferably compile with a fairly high level of alerts. This is especially important if you are starting out. For GCC the option is -Wall -Wextra . It will vary depending on the compiler you are using.

    
24.02.2014 / 23:17
2

Another tip: change the variable type new_sal to float. This will give you a more accurate answer to the output of your program. More information here . The final code looks like this:

#include <stdio.h>

int main (void)
{
   int sal;
   float novo_sal;
   printf ("Entre com sal");
   scanf ("%d", &sal);
   if (sal >= 1000) {
      novo_sal = 1.1 * sal;
      printf ("%f \n", novo_sal);
   }
   else {
      novo_sal = 1.2 * sal;
       printf ("%f \n", novo_sal);
  }
}
    
25.02.2014 / 04:05
0

Problem:

  

scanf ("%d, &sal");

25.02.2014 / 13:31