hex_bytes = { 0x1c, 0x01 }。 当我尝试打印十六进制值时,我得到的都是 0-6ren">
gpt4 book ai didi

c - 无法在 C 中打印返回数组指针的函数的输出

转载 作者:行者123 更新时间:2023-12-02 18:25:16 26 4
gpt4 key购买 nike

我正在尝试创建一个将十六进制字符串转换为十六进制字节数组的函数。示例:str = "1c01" -> hex_bytes = { 0x1c, 0x01 }

当我尝试打印十六进制值时,我得到的都是 0。我认为这与我的指针有关,但我不确定。任何帮助将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char *input_1 = "1c0111001f010100061a024b53535009181c";

unsigned int *str_to_hexbytes(const char *hex_str) {
size_t len = strlen(hex_str);
unsigned int *hex = malloc(sizeof(unsigned int)* len / 2);
for(int i, j = 0; i < len; i += 2, j++) {
char tmp[2];
strncpy(tmp, hex_str + i, 2);
hex[j] = strtol(tmp, NULL, 16);
}
return hex;
}

int main(void) {
size_t len = strlen(input_1) / 2;
unsigned int *hex = str_to_hexbytes(input_1);
for (int i = 0; i < len; i++) {
printf("%x ", hex[i]);
}
return 0;
}

最佳答案

tmp 只有足够的空间来存储您复制的两个字符。它没有有空间容纳空字节来终止字符串,事实上 strncpy 不会写入该空字节,因为它在读取的两个字符中没有找到一个。

因此,strtol 函数读取超出数组末尾的内容,从而触发 undefined behavior .

tmp 设为 3 个字符长并手动添加空字节。

此外,您仅初始化 j,而不是 i,因此请确保也这样做。

for(int i = 0, j = 0; i < len; i += 2, j++) { 
char tmp[3];
strncpy(tmp, hex_str+i, 2);
tmp[2]=0;
hex[j] = strtol(tmp, NULL, 16);
}

关于c - 无法在 C 中打印返回数组指针的函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70316677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com