1

I am confused as to why my program keeps on crashing. I am using Code Blocks, an open source IDE.

Here is the code:

int main()
{
  int age;
  char gender;

  printf("What is your age?\n");
  scanf(" %d", age);

  printf("What is your gender? \(m/f)\n");
  scanf(" %c", gender);

  if (age>=18){
    printf("Access granted! Please proceed\n");

    if (gender == 'm'){
      printf("What's up dude?");
    };
    if (gender == 'f'){
        printf("How's it going dudette?");
    };
  };
  if (age<18){
    printf("Access denied. Please get on with your life.\n");
  };

  return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
dmitrikonnikov
  • 53
  • 1
  • 1
  • 7
  • 1
    `scanf(" %d", &age);`, `scanf(" %c", &gender);` – BLUEPIXY Jan 16 '16 at 02:52
  • You don't need semicolons after your end-of-block `}` — they're mainly needed after enum, structure and union definitions, and initializers. Additionally, if your compiler is not telling you what's wrong with your calls to `scanf()`, you either need to turn on (a lot) more warnings or you need to be using a better compiler. – Jonathan Leffler Jan 16 '16 at 03:02
  • 2
    Also notice that C is not a language where you can be sure that if your code compiles, it will run without crashing. It is very easy to make code that compiles that will crash when run. (It's also a good idea to end the dude's and dudette's messages with a newline.) Except for the semicolon (null statement) before it, you could use `else` in place of `if (age < 18)`. – Jonathan Leffler Jan 16 '16 at 03:07
  • Please read more C books before asking beginners questions. You can choose a book from [here](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Box Box Box Box Jan 16 '16 at 03:32
  • As a general note for `scanf`, be aware that taking input with `scanf` will often leave the `'\n'` in the input buffer (`stdin`) after the conversion is performed. While some conversion specifiers will ignore whitespace (including the `'\n'`), e.g.: `%d`, etc., others will not, e.g. `%s`. It is well worth the time to *read* `man scanf` thoroughly to understand the distinctions. – David C. Rankin Jan 16 '16 at 05:59

1 Answers1

2

scanf requires a pointer to the variable you're setting. So, you need to do:

scanf(" %d", &age);

and similar for gender

bruceg
  • 2,433
  • 1
  • 22
  • 29