如何为这个结构malloc

时间:2012-07-12 14:38:38

标签: c malloc

typedef struct testMsg_ {
    unsigned char opCode;
    unsigned int  Count;
    char    *macsStrList[MAC_ADDR_STR_LEN];
} testMsg_t;

macsStrList中的元素数量是m_Count。

我知道以下是不正确的:

testMsg_t *pInput = (testMsg_t *) malloc(sizeof(testMsg_t) );

3 个答案:

答案 0 :(得分:3)

考虑到您已完成的结构, 正确

  

testMsg_t * pInput =(testMsg_t *)malloc(sizeof(testMsg_t));

然而,您可能会对*arr[dimension]的含义感到困惑 - 这是指向字符的指针的数组长度维度 - 在行之间读取,

  
    

MAC_ADDR_STR_LEN

  

可能是对mac地址的字符串表示的粗略(比如说< 20字节?)

但是你的struct会给你20个char指针,而且字符指针仍然必须初始化以指向有效的内存。

testMsg_t *pInput = (testMsg_t *) malloc(sizeof(testMsg_t) );
pInput->macsStrList[0] = (char *) malloc( MAC_ADDR_STR_LEN+1 );
pInput->macsStrList[1] = (char *) malloc( MAC_ADDR_STR_LEN+1 );
pInput->macsStrList[2] = (char *) malloc( MAC_ADDR_STR_LEN+1 );
...

或将您的结构重新定义为

typedef struct testMsg_ {
    unsigned char opCode;
    unsigned int  Count;
    char    macsStrList[NUMBER_OF_MAC_ADDRESSES][MAC_ADDR_STR_LEN];
} testMsg_t;

避免必须处理多个分配。

<强> ADDITION

根据评论,假设动态确定了mac地址的数量,你也可以将结构定义为;

typedef struct testMsg_ {
        unsigned char opCode;
        unsigned int  Count;
        char    macsStrList[1][MAC_ADDR_STR_LEN];
    } testMsg_t;

然后使用

分配它
testMsg_t *pInput = (testMsg_t *) malloc(sizeof(testMsg_t) + (countOfMacsAddresses * MAC_ADDR_STR_LEN) );

如果您需要这样做,可以使用realloc来动态调整数组大小的解决方案。

答案 1 :(得分:1)

我认为你想要的可能是(好吧,Soren先进入,但我会展示一种分配单个连续块的方法):

/* assuming we only need macStrList[0] ... [Count-1] */
struct testMsg
{
    unsigned char opCode;
    unsigned int  Count;
    char *macsStrList[];
};

struct testMsg *allocate_testMsg(int count)
{
    char *string_storage;
    struct testMsg *msg;

    size_t size = sizeof(struct testMsg)   /* base object */
                + (count * sizeof(char *)) /* char* array */
                + (count * (MAC_ADDR_STR_LEN+1)) /* char storage */
                ;

    msg = malloc(size);
    msg->Count = count;
    string_storage = (char *)&(msg->macStrList[count]);

    /* note msg->macStrList points to UNINITIALIZED but allocated storage.
       it might be sensible to zero-fill string_storage, depending on how you'll
       initialize it
    */
    for (count=0; count < msg->Count;
         ++count, string_storage += (MAC_ADDR_STR_LEN+1))
    {
        msg->macStrList[count] = string_storage;
    }

    return msg;
}

答案 2 :(得分:0)

当然是。您分配指向testMsg_t的指针,struct testMsg_是{{1}}的别名。但是,您需要自己初始化此对象。

(而且你不需要在C中转换分配的指针。)