c++ - 包含 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
是可变的。因此,每个实例都希望设置不同数量的它们。
解决方案
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;
};
推荐阅读
- prometheus - Prometheus remote_read 返回 405 Method Not Allowed
- java - 为什么我不能在我的项目中使用 JPA 创建 EntityManager?
- lua - 如何让 math.random 打印一个字符串
- r - 有没有办法更改 mlr3 中的默认公式?
- python - 尝试导入 numpy
- python - 如何用前几年相同时间范围的权重替换特定时间范围的值?
- r - 在 R 中创建手动表时遇到问题
- extjs - 如何开始使用 ExtJS 和 WebSharper?
- r - 从具有不同日期的两个文件夹中读取所有 CSV 文件的最佳方法 (LOOP)
- google-api - 用于查询 Google 群组对话的推荐 API 是什么?