January 2nd, 2013, 09:14 AM
Basic C programming
Hi folks. Can anyone tell me why this does not work?
#define BIT 8
printf("Type in a 8 bit number: ");
printf("Number of 1's: %d", bitCount(BYTE));
int bitCount(char x)
int counter = 0;
for (i = 0; i <= BIT; i++)
if (*x == 1)
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
January 2nd, 2013, 09:56 AM
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
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
January 2nd, 2013, 01:32 PM