我想创建一个将unsigned char转换为unsigned int并将其存储到数组中的函数。但是,最终会出现错误
从不兼容的指针类型传递'sprintf'的参数1。
int main(void) {
unsigned char key[16] = "1234567812345678";
phex(key, 16); //store into an array here
}
uint64_t* phex(unsigned char* string, long len)
{
uint64_t hex[len];
int count = 0;
for(int i = 0; i < len; ++i) {
count = i * 2;
sprintf(hex + count, "%.2x", string[i]);
}
for(int i = 0; i < 32; i++)
printf(hex[i]);
return hex;
}
答案 0 :(得分:1)
正如评论已经说过,你的代码有问题......
首先,sprintf
函数与您希望/期望它完全相反。接下来,在函数中创建一个局部变量,并返回指向它的指针。一旦函数退出,指针就无效了。我看到的第三个问题是你永远不会将回报值分配给任何东西......
关于如何修复代码的提议:
unsigned* phex(unsigned char* string, long len);
int main(void) {
int i;
unsigned char key[16] = "1234567812345678";
unsigned* ints = phex(key,16); //store into an array here
for(i = 0; i < 16; i++)
printf("%d ", ints[i]);
//never forget to deallocate memory
free(ints);
return 0;
}
unsigned* phex(unsigned char* string, long len)
{
int i;
//allocate memory for your array
unsigned* hex = (unsigned*)malloc(sizeof(unsigned) * len);
for(i = 0; i < len; ++i) {
//do char to int conversion on every element of char array
hex[i] = string[i] - '0';
}
//return integer array
return hex;
}