Thread: need help why code coredump(s)

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    2

    need help why code coredump(s)

    Hi folks,

    Im' a C newbie and I am working on some sample code. (please see below)

    Code:
    #include <stdio.h>
    main()
    {       
    
            int     mymood;
            char    type;
    
        printf("happy or sad [h/s]: ");
            scanf(" %c", type); 
            printf("type = %c\n", type);    
            mymood = type == 'h'; 
            if (mymood)
                    printf("My mood is happy\n");
            else 
                    printf("My mood is sad\n");
    
            getchar();
    
    }
    it compiles pretty well but when i try to run it and pick either 'h' or 's' it coredumps.. and I can't get it to work. =/

    any help would be awesomely appreciated.
    thanks,
    pfu
    Last edited by Salem; 10-23-2010 at 11:56 PM. Reason: Added [code][/code] tags - learn to use them yourself

  2. #2
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    404
    You need to change this line
    Code:
    scanf(" %c", type);
    to this
    Code:
    scanf(" %c", &type);
    scanf is looking for the address of the char, not the char itself.

    Also try and use code tags in the future

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Since you mention segfaults, does that mean you're using gcc and Linux?

    If so, use lots of compile flags to help you spot many dumb mistakes before you run the code.

    Eg.
    gcc -W -Wall -ansi -pedantic -O2 prog.c
    would have warned you about the missing & in the scanf call.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    2
    To all that have replied ..

    many thanks for the tips and response to my wimpy code.. that '&' did the fix.

    I really appreciate this awesome forum, now that im starting with C..

    thanks,
    -pfu

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Extended ASCII Characters in an RTF Control
    By JustMax in forum C Programming
    Replies: 18
    Last Post: 04-03-2009, 08:20 PM
  2. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  3. Obfuscated Code Contest
    By Stack Overflow in forum Contests Board
    Replies: 51
    Last Post: 01-21-2005, 04:17 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM