如何创建一个函数来计算结构数组的字符串项中的总字符数?

时间:2018-03-12 06:30:48

标签: c arrays

我定义了结构类型Monitor,并设置了P000P100 ..... 因为我不知道P000P100 ...中数组的大小。所以首先我需要知道数组的大小。然后根据数组的大小来计算Name中的数组项P000总字符数。

例如: 在数组P000中,数组大小为5,总字符数为27 char。我想使用一个像Uint16 CalculateCharacter(MonitorData P[])这样输入数组数据P000 P100的函数...然后计算这个数组的大小,使用这个数组大小来计算字符并返回这个值?谢谢!

    Uint16 CalculateCharacter(MonitorData P[])
typedef struct Monitor MonitorData;
 struct Monitor
    {
        int     No;
        char    *Name;
        int     Value;
    };
MonitorData P000[] =
    {
         { 0, "DA1_T/" , 0 },
         { 1, "DA2/" , 1 },
         { 2, "DA3_S/" , 1 },
         { 3, "DA4/" , 1 },
         { 4, "DITest/" , 0 },
    };
MonitorData P100[] =
    {
         { 0, "Teffdf/" , 0 },
         { 1, "ss/" , 1 },
         { 2, "rrd3/" , 1 },
         { 3, "ffff/" , 1 },
    };

1 个答案:

答案 0 :(得分:1)

根据我的理解,您正在寻找以下内容:

int countChars(MonitorData data[], int size) {
    int count = 0;
    for(int i = 0; i < size; i++)
        count += strlen(data[i].Name);

    return count;
}

int main(int argc, char const *argv[]) {
    int size = sizeof(P000) / sizeof(P000[0]);
    printf("%d\n", countChars(P000, size));
    return 0;
}

此函数采用MonitorData数组及其元素数。您可以通过获取其总大小(以字节为单位)并除以第一个元素的大小来查找其元素数。然后,对于数组中的每个元素,该函数将计数增加每个Name字段的长度。希望这会有所帮助:)