#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    3
    Rep Power
    0

    Smile Basic C programming


    Hi folks. Can anyone tell me why this does not work?

    #include <stdio.h>
    #define BIT 8

    int main(void)
    {
    char BYTE[BIT];

    printf("Type in a 8 bit number: ");
    scanf("%as", BYTE);
    printf("Number of 1's: %d", bitCount(BYTE));

    return bitCount(BYTE);
    }

    int bitCount(char x[])
    {
    int counter = 0;
    int i;
    for (i = 0; i <= BIT; i++)
    {
    if (*x == 1)
    counter++;
    x++;
    }
    return counter;
    }

    The results are allways 0. The bitCount function works as I tested it with a fixed number, but i wanted the scanf function. What do I do wrong here? :) Thanks
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,407
    Rep Power
    1871
    1. You didn't use [code][/code] tags when posting code.

    2. scanf("%as", BYTE);
    This doesn't do what you think it does.
    %as when compiled with glibc allocates space for a string.

    3. Any string you type in will have a \0. So to store 8 characters and a \0, you need at least char[9]

    4. for (i = 0; i <= BIT; i++)
    This is a buffer overrun.
    The idiomatic for loop for accessing an array is
    for (i = 0; i < BIT; i++)

    5. if (*x == 1)
    If you typed in "10011010", then you need to compare with '1' not 1
    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. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    3
    Rep Power
    0
    Thanks :thumbs:

IMN logo majestic logo threadwatch logo seochat tools logo