无法将struct传递给结构中的指针

时间:2014-02-07 22:39:30

标签: c pointers struct

鉴于以下定义:

#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");
*/

2 个答案:

答案 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;