Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.88 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. how to malloc for this structure
  2. typedef struct testMsg_ {
  3.     unsigned char opCode;
  4.     unsigned int  Count;
  5.     char    *macsStrList[MAC_ADDR_STR_LEN];
  6. } testMsg_t;
  7.        
  8. testMsg_t *pInput = (testMsg_t *) malloc(sizeof(testMsg_t) );
  9.        
  10. testMsg_t *pInput = (testMsg_t *) malloc(sizeof(testMsg_t) );
  11. pInput->macsStrList[0] = (char *) malloc( MAC_ADDR_STR_LEN+1 );
  12. pInput->macsStrList[1] = (char *) malloc( MAC_ADDR_STR_LEN+1 );
  13. pInput->macsStrList[2] = (char *) malloc( MAC_ADDR_STR_LEN+1 );
  14. ...
  15.        
  16. typedef struct testMsg_ {
  17.     unsigned char opCode;
  18.     unsigned int  Count;
  19.     char    macsStrList[NUMBER_OF_MAC_ADDRESSES][MAC_ADDR_STR_LEN];
  20. } testMsg_t;
  21.        
  22. typedef struct testMsg_ {
  23.         unsigned char opCode;
  24.         unsigned int  Count;
  25.         char    macsStrList[1][MAC_ADDR_STR_LEN];
  26.     } testMsg_t;
  27.        
  28. testMsg_t *pInput = (testMsg_t *) malloc(sizeof(testMsg_t) + (countOfMacsAddresses * MAC_ADDR_STR_LEN) );
  29.        
  30. /* assuming we only need macStrList[0] ... [Count-1] */
  31. struct testMsg
  32. {
  33.     unsigned char opCode;
  34.     unsigned int  Count;
  35.     char *macsStrList[];
  36. };
  37.  
  38. struct testMsg *allocate_testMsg(int count)
  39. {
  40.     char *string_storage;
  41.     struct testMsg *msg;
  42.  
  43.     size_t size = sizeof(struct testMsg)   /* base object */
  44.                 + (count * sizeof(char *)) /* char* array */
  45.                 + (count * (MAC_ADDR_STR_LEN+1)) /* char storage */
  46.                 ;
  47.  
  48.     msg = malloc(size);
  49.     msg->Count = count;
  50.     string_storage = (char *)&(msg->macStrList[count]);
  51.  
  52.     /* note msg->macStrList points to UNINITIALIZED but allocated storage.
  53.        it might be sensible to zero-fill string_storage, depending on how you'll
  54.        initialize it
  55.     */
  56.     for (count=0; count < msg->Count;
  57.          ++count, string_storage += (MAC_ADDR_STR_LEN+1))
  58.     {
  59.         msg->macStrList[count] = string_storage;
  60.     }
  61.  
  62.     return msg;
  63. }
  64.        
  65. testMsg_t* myPointer = (testMsg_t*) malloc(sizeof(testMsg_t));