- 论坛徽章:
- 0
|
看别人的代码,函数功能为创建消息队列- typedef unsigned int U32
- typedef struct {
- sem_t sem;
- pthread_mutex_t mutex;
- U32 u32MsgSize; //消息大小
- U32 u32MaxMsgs; //消息队列中所能容纳的最多消息数
- [color=Red] void *msgs; [/color] //消息指针
- U32 u32HeaderIdx; //当前消息序号
- U32 u23MsgNum;// the number of existing msgs in the message queue
- }MsgInfo_t;
复制代码- S32 MsgQCreate( U32 u32MsgSize, U32 u32MaxMsgNum )
- {
- MsgInfo_t *mmsg = NULL;
- [color=Red] mmsg = malloc(sizeof(MsgInfo_t)+u32MsgSize*u32MaxMsgNum);[/color]
- if ( NULL== mmsg )
- {
- return FAIL;
- }
- memset( mmsg , 0 , sizeof(MsgInfo_t) );
- mmsg->u32MsgSize = u32MsgSize;
- mmsg->u32MaxMsgs = u32MaxMsgNum;
- [color=Red]mmsg->msgs = (void *)( mmsg+1 );[/color]
- mmsg->u32HeaderIdx = 0;
- mmsg->u23MsgNum = 0;
- pthread_mutex_init( &mmsg->mutex , NULL );
- sem_init( &mmsg->sem, 0, 0 );
- return OK;
- }
复制代码 本人菜鸟,
1.我想请问这句代码
mmsg->msgs = (void *)( mmsg+1 );
为什么msgs等于mmsg+1,
mmsg为指向结构体MsgInfo_t的指针,而msgs包含在结构体MsgInfo_t中,按定义,从mmsg开始的一段内存空间应该先保存sem,mutex,u32MsgSize,u32MaxMsgs,然后
才保存msgs指向的内容,可不应该加1啊,请指教
2.如果一个结构体里包含指针变量,我为该结构体申请内存空间,那结构体里的指针是不是需要初始化或申请内存空间呢?还是不用,因为在为结构体申请内存时已经完成了对结构体内指针的初始化?请指教
|
|