我正在尝试迭代一个单一的 const unsigned char
数组,并使用类型转换将每个元素赋值/转换为一个新的 char
数组。虽然我已经阅读了许多线程,建议使用类型转换,但它对我没有起作用。以下是我的尝试:
#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;
}
以上代码的标准输出:
期望得到的标准输出为:
1111111111
如何将nums中的元素转换为char类型并有效地将转换后的值分配/存储到new数组中?