简体   繁体   中英

How to get the length of all strings in an object in C

I have a structure which includes 7 different strings in it. I need to find the total length of those strings in the object. Here is my type:

typedef struct
{
    char activity   [250]; 
    char adv_MAC    [250];   
    char PTx        [250]; 
    char refRSSI    [250]; 
    char RSSI       [250]; 
    char tick       [250];  
    char locatorID  [250];  
} report_data_t;   /**< BLE temporary report data struct */

I'm not looking for the size of the object. I'm lokking for the length of each string in the object. I already tried to use

strlen(o1.activity);

But my purpose is to achieve this in the shortest way.

As usual it's not clear what "short" means: are you after compact code, or high performance?

Since it's a lot of structure to exploit, I might go for a data-driven approach:

size_t report_strlen(const report_data_t *r)
{
  static const size_t strs[] = {
    offsetof(report_data_t, activity), offsetof(report_data_t, adv_MAC),
    offsetof(report_data_t, PTx),      offsetof(report_data_t, refRSSI),
    offsetof(report_data_t, RSSI),     offsetof(report_data_t, tick),
    offsetof(report_data_t, locatorID),
  };
  size_t len = 0;
  for (int i = 0; i < sizeof strs / siezof *strs; ++i)
  {
    len += strlen((const char *) r + strs[i]);
  }
  return len;
}

On second thought, it's probably not worth it and I'd just stack in all the explicit calls to strlen() , that's more approachable and 7 is not quite many enough to warrant the above.

A proper way would be to simply enumerate the memmbers:

size_t sz = 0;
sz+=strlen(d->activity);
sz+=strlen(d->adv_MAC);
sz+=strlen(d->PTx);
sz+=strlen(d->refRSSI);
sz+=strlen(d->RSSI);
sz+=strlen(d->tick);
sz+=strlen(d->locatorID);

It's pretty easy to type with a smart editor.

In your case, you could also simply do:

size_t sz = 0; for(int i=0;i<7;i++) sz+=strlen(&d->activity[250*i]);

while asserting that there's no padding (the standard doesn't guarantee it but for a struct consisting of only chars it should be true):

_Static_assert(sizeof(report_data_t)==7*250,"");

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