I try to assign some information to 'char' data (one structure and one integer value), but after i assign it i can't read it back. Any solution? I work on Ubuntu 16.04 installed on virtualbox
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;
}
Displayed text: Request opcode: 0x00000001 Request id: 0 Int value: 0
but Int value should be equal to '512'
You're dereferencing buff+sizeof(rq)
, which is a char *
. Since 512 is 0x 02 00
, if you dereference it as a char *
you get 0x00
. If you look in buff+sizeof(rq) + 1
, you get the other 0x02
.
On the other hand, if you cast the pointer to int *
, then you get the full 0x0200
.
printf("Int value: %d\n", *(int *)(buff+sizeof(rq)));
outputs 512.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.