我想制作一个将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;
}
最佳答案
正如评论所言,您的代码有问题...
首先,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;
}
关于c - 将unsigned char(数组)转换为unsigned int(数组),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40929278/