gpt4 book ai didi

将 char 指针转换为 unsigned char 数组

转载 作者:太空狗 更新时间:2023-10-29 17:11:17 25 4
gpt4 key购买 nike

我想将一个 char 指针转换为一个 unsigned char var,我以为我可以通过强制转换来做到这一点,但它不起作用:

char * pch2;
//Code that puts something in pc2
part1 = (unsigned char) pch2;

我有代码:

result.part1 = (unsigned char *) pch2;
printf("STRUCT %s\n",result.part1);

result 只是一个带有 unsigned char 数组的结构。

编辑:

            pch2 = strtok( ip, "." );

while( pch2 != NULL ){
printf( "x %d x: %s\n", i, pch2 );
pch2[size-1] = '\0';

if(i == 1)
result.part1 = (unsigned char *) pch2;
if(i == 2)
result.part2 = (unsigned char *) pch2;
if(i == 3)
result.part3 = (unsigned char *) pch2;
if(i == 4)
result.part4 = (unsigned char *) pch2;
i++;
pch2 = strtok (NULL,".");
}
printf("STRUCT %c\n",result.part1);

结构:

typedef struct
{
unsigned char part1;
unsigned char part2;
unsigned char part3;
unsigned char part4;
} res;

最佳答案

您转换为 unsigned char 而不是 unsigned char* 您忘记了 *

part1 = (unsigned char*) pch2;

如果 pch2 不是 null 终止程序将崩溃,如果你幸运的话,当你使用 strlen 时,所以你需要在使用打印之前先将它 null 终止pch2,试试这个:

pch2[size-1] = '\0';  /* note single quote */
result.part1 = (unsigned char *) pch2;

更新:像这样定义你的结构:

typedef struct
{
const char *part1;
const char *part2
const char *part3;
const char *part4;
} res;

并在完全不强制转换的情况下分配给它:

result.part1 = pch2;

关于将 char 指针转换为 unsigned char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13553752/

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