简体   繁体   中英

Designing structure with number of char array field in it

I have following Structure in my Program.

#define WIFI_DEVICE_NAME 100
#define WIFI_SERIAL_NO 13       
#define WIFI_PROD_NAME 7


typedef struct WiFiDeviceInfo
{
    char name[WIFI_DEVICE_NAME];                
    char fullname [WIFI_DEVICE_NAME];               
    char productname[WIFI_PROD_NAME];               
    char serialnumber[WIFI_SERIAL_NO];              
};

This Struct is used in the various places. Some time some of the fields may remain empty. So while copying using strcpy_s() , it fails. So I tried with strlen() before doing any copy operation.

I modified the struct and came up with the following design.

typedef struct WiFiDeviceInfo
{
    char name[WIFI_DEVICE_NAME];    
    unsigned short nLenName;            
    char fullname [WIFI_DEVICE_NAME];   
    unsigned short nLenFullName;            
    char productname[WIFI_PROD_NAME];
    unsigned short nproductname;                            
    char serialnumber[WIFI_SERIAL_NO];              
};

I can't use STL here since its legacy code, which doesn't use STL. Is there any better way to design the structure.

This modification is good. Since you are now storing the actual length of string using the member variables, I would suggest that you use pointers to char and allocate required memory at runtime. This would be useful from memory perspective. I mean you should do this...

    typedef struct WiFiDeviceInfo
    {
          char* name;    
          unsigned short nLenName;            
          char* fullname;   
          unsigned short nLenFullName;            
          char* productname;
          unsigned short nproductname;                            
          char* serialnumber;    // Convert the serialnumber to a pointer as well
          unsigned short nserialnumber;
    };

Add constructor and destructor to the struct to handle memory, like setting to NULL, delete pointers etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM