我想创建一个函数,将 unsigned char 转换为 unsigned int 并将其存储到数组中。然而,这最终会出现一个错误,显示
passing argument 1 of 'sprintf' from incompatible pointer type.
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;
}
最佳答案
正如评论已经说过的,你的代码有问题...... 首先, 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;
}
关于将 unsigned char(数组)转换为 unsigned int(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929278/