I am trying to iterate over a single const unsigned char array and assign/convert each element to a new char array using typecasting, every thread I've read suggests using typecasting however it's not working for me, here's my attempt:
#include <stdio.h>
#include <stdlib.h>
char *create_phone_number(const unsigned char nums[10]) {
char *new = malloc(11);
int i = 0;
for (; i<10; i++)
new[i] = (char)nums[i];
new[i] = '\0';
return new;
}
int main(void) {
char *num = create_phone_number((const unsigned char[]){ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });
printf("%s\n", num);
free(num);
return 0;
}
The above code's stdout:
Expected stdout:
1111111111
How do I convert the elements in nums to type char and assign/store the converted values in the new array (efficiently)?
Casting to
chardoesn't mean casting the integer value to the corresponding ASCII character; the numeric value 1 is the ASCII code SOH (start of heading) which has no printable representation, thus your empty output. If you know all the values will be in the range 0 to 9, you can add them to ASCII'0'to get thecharvalue that produces the associated ASCII digit:You don't actually need to cast it at all; the result of the
+will beintand it will store back to acharthat can fit it without issue (so just make sure they're really all0-9values, or you'll get weird results).