aslad aslad - 2 months ago 6
C Question

Converting decimal to binary error (C)

I've recently started programming in C and I really can't find the error here no matter how hard I try.

char* dec2Bin(int number) {
char* bin = calloc(9, sizeof(char));
if(bin!=NULL) {
bin[8] = '\0';
int i = 7;
while(number != 0 && i>=0){
bin[i] = (number%2) +'0';
number/=2;
i--;
}
}
return bin;
}


int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);

char* bin = dec2Bin(number);
if(bin!=NULL) {
printf("%s", bin);
free(bin);
return EXIT_SUCCESS;
}

return EXIT_FAILURE;
}


It displays nothing after I enter the number and oddly when I do a printf in the function loop it does print something for bin[i].

Thanks in advance for you help.

Answer

void *calloc(size_t nmemb, size_t size) allocates nmemb number of memory blocks and initializes them with 0 which gets typecasted to \0 character for this scenario. Now, printf will print the bin string until it gets a \0 character. Lets take a example. If I input 12 output should be 1100. But in your bin string it is \0\0\0\01100\0. And thus printf stops printing after it encounters the first \0 character.

Comments