Crash after reading value with scanf

Asked

Viewed 150 times

5

First, I am "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 I created, however, after compiling and writing a value, the 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?

3 answers

7

I suppose you meant to say

scanf ("%d", &sal);

in place 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 place this number in an unspecified memory place".

Writing in 'random' pieces of memory will usually cause you a 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 warning your compiler gives you. And preferably Compile with a fairly high level of alerts. This is important especially if you are getting started. For GCC the option is -Wall -Wextra. It will vary depending on the compiler you are using.

2

Another tip: change the type of the new variable to float. This way you will have a more precise answer in your program output. More info here. The final code would look 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);
  }
}

0

Problem:


scanf ("%d, &sal"); <- You can’t leave all the content of scanf in quotes.


Correction:


scanf ("%d", &sal); <- The variable that will receive the value of input cannot be inside quotes. &sal


Observation: Do not leave variables inside quotation marks, otherwise they will be marked as a simple "Text".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.