I've got a very very simple function which simply converts a char to a char* which represents the binary value of the char with 0's and 1's as chars.
char* stringToBin(char symbol) {
int pos = 0;
int value = (int) symbol;
int rest;
char* result = (char*) malloc(sizeof(char) * 9);
while(value > 0) {
if(value % 2 == 0) {
result[7-pos] = '0';
}
else {
result[7-pos] = '1';
}
pos++;
value = value / 2;
}
while(pos < 8) {
result[7-pos] = '0';
pos++;
}
result[8] = '\0';
puts(result);
puts(strlen(result));
return result;
}
My problem is I can't print the length of the char*. Printing the whole char* works perfect but not calculating the size. I alway get a segmentation fault. I think the problem is pretty simple but I did not get it right now. So please give me the missing hint ;)
The problem is not with the NUL-termination of your string, that's fine. Instead,
puts(strlen(result));
is wrong. puts()
expects a C string, and you're giving it a size_t
. Write instead:
printf("%zu\n", strlen(result));
(This assumes that the C99 format specifier %zu
for size_t
is available. If it isn't, then use:
printf("%u\n", (unsigned)strlen(result));
instead.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.