[英]C++: how to assign static array to a pointer inside a struct
I have C-code that I need to compile to C++ and need to minimally change it. 我有C代码,我需要编译到C ++,并需要最低限度地改变它。
In C, the following works 在C中,以下工作
typedef struct _type_t
{
int a;
int b;
int c[];
}type_t;
type_t var = {1,2,{1,2,3}};
But in C++11, it gives the error 但是在C ++ 11中,它给出了错误
error: too many initializers for
int [0]
错误:
int [0]
初始化程序太多
But I cannot give type_t.c
a constant size because it needs to work for any size array. 但我不能给
type_t.c
一个恒定的大小,因为它需要适用于任何大小的数组。
So I need to change the struct to 所以我需要将结构更改为
typedef struct _type_t
{
int a;
int b;
int *c;
}type_t;
But then I need to change 但后来我需要改变
type_t var = {1,2,{1,2,3}};
to something else because current code gives the error 因为当前代码会给出错误
error: braces around scalar initializer for type
int*
错误:类型为
int*
标量初始化器周围的大括号
Casting 3rd element to (int[])
gives error 将第3个元素转换为
(int[])
会产生错误
error: taking address of temporary array
错误:获取临时数组的地址
This is from micropython, parse.c : 这是来自micropython,parse.c :
#define DEF_RULE_NC(rule, kind, ...) static const rule_t rule_##rule = { RULE_##rule, kind, #rule, { __VA_ARGS__ } };
How do I initialize the array and assign it to type_t.c
? 如何初始化数组并将其分配给
type_t.c
?
Use std::vector and aggregate initialization : 使用std :: vector和聚合初始化 :
struct type_t
{
int a;
int b;
std::vector<int> c;
};
int main() {
type_t var = { 1, 2, { 1, 2, 3 } };
}
In order to do this you need to make your array really static: 为此,您需要使您的数组非常静态:
typedef struct _type_t
{
int a;
int b;
int * c;
}type_t;
int items[3] = {1,2,3};
type_t var = {1,2, static_cast< int * >(items)};
C++ doesn't allow this statement expression. C ++不允许使用此语句表达式。 You may use lightweight
std::initialiser_list
to achieve the objective 您可以使用轻量级
std::initialiser_list
来实现目标
#include <initializer_list>
typedef struct _type_t
{
int a;
int b;
std::initializer_list<int> c;
}type_t;
type_t var = {1,2,{1,2,3,4}};
yet another alternative might be 另一种选择可能是
...
int * c;
}type_t;
type_t var = {1,2, []{ static int x[] = {1,2,3}; return x; }() };
PS: yes, I know it's crazy, but it's somewhat more respectful of OP requirements ( it can be incorporated in a dropin replacement macro as given ) PS:是的,我知道它很疯狂,但它更加尊重OP要求(它可以被合并到dropin替换宏中)
In C++ arrays are stored in stack memory so you must have to specify array size on the time of declaring it. 在C ++中,数组存储在堆栈内存中,因此必须在声明数据时指定数组大小。 If you want to declare array with arbitrary size use
vector
or do this 如果要使用任意大小声明数组,请使用
vector
或执行此操作
struct type_t
{int a;
int b;
int *c = new int[size];
}var{1,2,{1.,..}};
Here size
is any arbitrary integer and {1.,..}
are values of elements of dynamic array seperated by comma. 这里的
size
是任意整数, {1.,..}
是由逗号分隔的动态数组元素的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.