Reputation: 4970
I have C-code that I need to compile to C++ and need to minimally change it.
In C, the following works
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
error: too many initializers for
int [0]
But I cannot give type_t.c
a constant size because it needs to work for any size array.
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*
Casting 3rd element to(int[])
gives error
error: taking address of temporary array
This is from 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
?
Upvotes: 3
Views: 957
Reputation: 5624
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 )
Upvotes: 0
Reputation: 349
C++ doesn't allow this statement expression. You may use lightweight std::initialiser_list
to achieve the objective
#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}};
Upvotes: 1
Reputation: 37487
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)};
Upvotes: 6
Reputation: 15501
Use std::vector and aggregate initialization:
struct type_t
{
int a;
int b;
std::vector<int> c;
};
int main() {
type_t var = { 1, 2, { 1, 2, 3 } };
}
Upvotes: 7