我试图在struct中指向一个内存地址:
typedef struct {
uint32_t dataAddress;
} response_struct;
到初始化的数组:
uint8_t *msg = NULL;
msg = malloc(sizeof(uint8_t)*LEN);
printf("Init: \n");
for (i=0; i<LEN; i++) {
msg[i] = i;
printf("%d ", msg[i]);
}
,在分配后,它可以正确显示其内容:
// case 1:
(response_struct_ptr->dataAddress) = (uint32_t) msg;
// or with case 2:
void assign_value_to_memory_address_given (uint8_t *msg, response_struct *response_struct_ptr) {
(response_struct_ptr->dataAddress) = (uint32_t) msg;
}
// e.g. assign_value_to_memory_address_given (msg, response_struct_ptr);
显示遇到分段错误(核心已转储)
for (i=0; i < LEN; i++) // message fixed at length 10
printf(" %x", ((uint8_t*) response_struct_ptr->dataAddress)[i]);
printf("\n");
有人可以指出哪里不正确吗? 谢谢。
答案 0 :(得分:1)
该代码可能适用于32位设备,但不适用于64位设备。
如@melpomene所建议,如果您使用的是64位平台,则因为指针不适合32位。因此,可以通过更改类型来对代码进行补救:
typedef struct {
//uint32_t dataAddress;
uint8_t *dataAddress;
} response_struct;
并由@immibis建议修正代码行:
//(response_struct_ptr->dataAddress) = (uint32_t) msg;
(response_struct_ptr->dataAddress) = msg;