I don't seem to be understanding how printf() formats the output of char arrays in C. I have a bit of code whose purpose is to translate an integer into a string of binary characters, and print it. The code works up to the point where I go to print the string returned from integerToString(), because it doesn't print the contents of the string.
I've checked gdb to ensure that both res and str contained an array of the correct values before the printf() call. I've also tried printing *res instead of just res, but that returns (null). What am I missing? Is there something about pointers that I am not grasping?
Thanks much in advance.
#include<stdio.h>
#include<stdlib.h>
int main () {
printf("Please enter a positive integer: ");
unsigned int input;
scanf("%d", &input);
char* res = integerToString(input);
printf("Represented in binary that integer is: %s\n", res);
}
char* integerToString(unsigned int number){
unsigned int value = number;
char* str;
str = malloc(33); //32 bits for the string, +1 null value on the end
unsigned int i = 31;
while (i > 0){
str[i] = value % 2;
value /= 2;
i--;
}
str[32] = '\0';
return(str);
}
printf("%032b", input)isn't good enough?str[i] = value % 2should bestr[i] = value % 2 + '0''0'and0are not the same thing.%bis not standard C – though it may be fairly widely available.mallocwithout callingfree!