指针的值显示不正确
Value from the pointer is not displaying correctly
我尝试将一些信息分配给 'char' 数据(一个结构和一个整数值),但是在我分配它之后我无法读回它。任何解决方案?我在 virtualbox
上安装 Ubuntu 16.04
struct opcode_struct{
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d;
};
union opcode{
uint32_t uint32code;
struct opcode_struct code;
};
struct request{
//4
union opcode opc;
//4
uint32_t id;
};
int main()
{
char *buff = (char*)malloc(32);
struct request rq = {0x00000001, 0}, *ptr_rq = &rq;
int val = 512, *ptr_int = &val;
memcpy(buff, ptr_rq, sizeof(rq));
memcpy((buff+sizeof(rq)), ptr_int, sizeof(int));
printf("Request opcode: 0x%08x\n", *buff);
printf("Request id: %d\n", *(buff+sizeof(uint32_t)));
printf("Int value: %d\n", *(buff+sizeof(rq)));
free(buff);
return 0;
}
显示的文字:
请求操作码:0x00000001
请求编号:0
整数值:0
但 Int 值应等于“512”
您正在取消引用 buff+sizeof(rq)
,这是 char *
。由于 512 是 0x 02 00
,如果您将其取消引用为 char *
,您将得到 0x00
。如果你查看 buff+sizeof(rq) + 1
,你会得到另一个 0x02
。
另一方面,如果您将指针转换为 int *
,那么您将获得完整的 0x0200
。
printf("Int value: %d\n", *(int *)(buff+sizeof(rq)));
输出 512。
我尝试将一些信息分配给 'char' 数据(一个结构和一个整数值),但是在我分配它之后我无法读回它。任何解决方案?我在 virtualbox
上安装 Ubuntu 16.04struct opcode_struct{
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d;
};
union opcode{
uint32_t uint32code;
struct opcode_struct code;
};
struct request{
//4
union opcode opc;
//4
uint32_t id;
};
int main()
{
char *buff = (char*)malloc(32);
struct request rq = {0x00000001, 0}, *ptr_rq = &rq;
int val = 512, *ptr_int = &val;
memcpy(buff, ptr_rq, sizeof(rq));
memcpy((buff+sizeof(rq)), ptr_int, sizeof(int));
printf("Request opcode: 0x%08x\n", *buff);
printf("Request id: %d\n", *(buff+sizeof(uint32_t)));
printf("Int value: %d\n", *(buff+sizeof(rq)));
free(buff);
return 0;
}
显示的文字: 请求操作码:0x00000001 请求编号:0 整数值:0
但 Int 值应等于“512”
您正在取消引用 buff+sizeof(rq)
,这是 char *
。由于 512 是 0x 02 00
,如果您将其取消引用为 char *
,您将得到 0x00
。如果你查看 buff+sizeof(rq) + 1
,你会得到另一个 0x02
。
另一方面,如果您将指针转换为 int *
,那么您将获得完整的 0x0200
。
printf("Int value: %d\n", *(int *)(buff+sizeof(rq)));
输出 512。