鉴于以下定义:
#define arrayLengthInStruct 50
typedef struct {
int _buf[arrayLengthInStruct];
int _bufLen;
} list;
// nested struct seems redundant but is there for some specific use
struct dev_req {
struct {
struct {
int src;
}serviceReq;
}_req;
};
在main()
中 int i=0;
// to pass the memory location
list g_src; // data is here
struct dev_req *dev_Areq; // to be loaded/ transfer to here
g_src._bufLen = arrayLengthInStruct;
// initialize the source
for (i = 0; i < g_src._bufLen; i++) {
g_src._buf[i] = i+1;
printf("%d \t", g_src._buf[i]);
}
printf("\n");
接下来的两行失败
//dev_Areq->_req.serviceReq.src = malloc(sizeof(g_src)); // failed
//dev_Areq->_req.serviceReq.src = (list*) &g_src; // failed
即使在通过之前的1行之后,下一部分是否仍然有用也是不清楚的。
/*
for (i = 0; i < (dev_Areq->_req.serviceReq.src)->_bufLen; i++) {
printf("%d \t", (dev_Areq->_req.serviceReq.src)->_buf[i]);
}
printf("\n");
*/
答案 0 :(得分:1)
dev_Areq->_req.serviceReq.src
是一个整数,您正在尝试为其指定指针。这是错误的。
答案 1 :(得分:1)
首先,dev_Areq
是指针类型,它指向尚未分配的内存。
dev_Areq = (struct dev_req *)malloc(sizeof(struct dev_req ));
只有在此之后,您才能访问其_req
元素。
第二,您希望将src
指向list
类型并访问其元素,然后您应将src
定义为list *
类型,而不是int
。然后使用此行将src
指向g_src
:
dev_Areq->_req.serviceReq.src = (list*) &g_src;