首页 > 解决方案 > 包含 char 数组的结构体

问题描述

我正在尝试定义一个结构的实例,并且在设置这个变量时遇到了特别的麻烦。它是一个 char 数组。

这是我的头文件中的结构...

struct widget_t {
    char *name;
    uint8_t numberOfNicknames;
    char *nicknames[];
};

这是我试图设置widget_t结构的实例......

widget_t SomeWidget;

void setUpFunction () {
    SomeWidget.name = (char *)"Lawn Mower";
    SomeWidget.numberOfNicknames = 2;
    SomeWidget.nicknames = {
        "Choppie McGrasschopper",
        "Really Noisy"
    };
}

因此,当我尝试将昵称放入SomeWidget.nicknames. 我不确定我是否需要做一些时髦的事情,就像我正在做name的指针一样......?

棘手的一点是数量nicknames是可变的。因此,每个实例都希望设置不同数量的它们。

标签: c++arduinoflexible-array-member

解决方案


The problem you have, is that c++ does not support variable arrays. Instead you will have to allocate memory dynamically using new or in your case new[].

First you need to change your data type to char**, almost equaliant to the one before. Then you can allocate as many strings you want like this nicknames = new char*[number_of_nicknames].

Important is that with this method you will have to delte your nicknames manually like this: delete[] nicknames;. The best way to accomplish this is using RAII (delete your nicknames in your deconstructor)

When you have dynamic strings then you would use the following structure

struct widget_t {
    // optional constructor to allocate nicknames

    ~widget_t()
    {
        for (int i = 0; i < numberOfNicknames; ++i)
        {
            char* nickname = nicknames[i];

            if (nickname)
                delete[] nickname;
        }

        delete[] nicknames;
    }

    char *name;
    uint8_t numberOfNicknames;
    char **nicknames = NULL;
};

and with constant string the next

struct widget_t {
    // optional constructor to allocate nicknames
    // allocate nicknames like
    // -> nicknames = new const char*[numberOfNicknames];

    ~widget_t()
    {
         if (nicknames) delete[] nicknames;
    }

    char *name;
    uint8_t numberOfNicknames;
    const char **nicknames = NULL;
};

推荐阅读