我想将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);
STRUCT:
typedef struct
{
unsigned char part1;
unsigned char part2;
unsigned char part3;
unsigned char part4;
} res;
答案 0 :(得分:3)
你转为unsigned char
而不是unsigned char*
你忘记了*
part1 = (unsigned char*) pch2;
如果pch2
未终止,程序将崩溃,如果您很幸运,当您使用strlen
时,您需要在使用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;
答案 1 :(得分:1)
你想这样做:
part1 = (unsigned char*) pch2;
而不是:
part1 = (unsigned char) pch2;
答案 2 :(得分:1)
尝试这样的事情: -
char *ph2;
unsigned char *new_pointer = (unsigned char*) ph2;
答案 3 :(得分:1)
你确定吗?将指向char的指针转换为unsigned char不会有任何好处 - 值将被截断为1个字节,无论如何它都将毫无意义。也许你想取消引用一个指针并获得它指向的值 - 那么你应该做这样的事情:我想将char指针转换为unsigned char var
unsigned char part1 = (unsigned char)*pch2;
编辑后,我看到part1
是字符数组 - 如果程序在使用后崩溃,您可能会错误填写pch2
。也许你忘记了'\0'
终结者?
编辑:
你知道,现在回答你所有必需信息的问题要好得多。你需要使用strtok
吗?这会好吗?
res result;
char* ip = "123.23.56.33";
sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &result.part1, &result.part2, &result.part3, &result.part4);
答案 4 :(得分:0)
发现问题,忘了将char pch2强制转换为unsigned int然后我可以用%u打印输出。 代码:
unsigned int temp;
temp = atoi(pch2);
result.part1 = temp;
printf("Struct: %u\n",result.part1);
感谢您的帮助!