jeudi 2 novembre 2017

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.

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

How do I initialize the array and assign it to type_t.c ?

Aucun commentaire:

Enregistrer un commentaire