user2166351
user2166351

Reputation: 183

Cannot assign array to struct property

I'm just learning C, and I'm having problems with assigning an array to a property (pulses).

I have a struct:

typedef struct irPulseSet
{
    int pulseCount;
    int pulses[][2];
} irPulseSet;

I create a new variable with the irPulseSet type that I created above, and define an array:

irPulseSet upButton;

upButton.pulseCount = 31;
int upButtonPulses[31][2] = 
{
    { 0 , 120 },
    { 440 , 360 },
    { 440 , 340 },
    { 440 , 1120 },
    { 420 , 380 },
    { 420 , 360 },
    { 400 , 1140 },
    { 420 , 1120 },
    { 420 , 380 },
    { 420 , 1140 },
    { 420 , 1120 },
    { 440 , 340 },
    { 440 , 360 },
    { 440 , 1120 },
    { 440 , 1120 },
    { 420 , 1120 },
    { 400 , 1140 },
    { 420 , 360 },
    { 440 , 340 },
    { 440 , 360 },
    { 440 , 1140 },
    { 440 , 360 },
    { 440 , 340 },
    { 440 , 380 },
    { 420 , 360 },
    { 440 , 1120 },
    { 440 , 1120 },
    { 440 , 1120 },
    { 440 , 27400 },
    { 7160 , 1500 },
    { 0 , 0 }
};

I then assign that array to a property in the irPulseSet struct.

upButton.pulses = upButtonPulses;

But when I compile, I get the error:

invalid use of flexible array member

What am I doing wrong here?

Upvotes: 0

Views: 446

Answers (3)

Aman Kaushal
Aman Kaushal

Reputation: 124

error due to

int pulses[][2];

you need to define size !! try it once.

Upvotes: 0

MBlanc
MBlanc

Reputation: 1783

What am I doing wrong here?

You are making an assignment (=) to an array-type. See self.'s answer points in the right direction if you want both the structure and the array to point to the same place in memory. However, if you want a copy of the data, read on.


invalid use of flexible array member

The reason you're getting this error, is that to use a flexible array member, you must allocate the extra space for the array, for example when you malloc'd it. Eg.

irPulseSet upButton = malloc(sizeof(irPulseSet) + sizeof(upButtonPulses));
memcpy(upButton->pulses, upButtonPulses, sizeof(upButtonPulses));

Upvotes: 0

this
this

Reputation: 5290

You have to change the type of the pulses member in the struct to a pointer to a 2d array, before you had a flexible array member which you have allocate dynamically.

typedef struct irPulseSet
{
    int pulseCount;
    int (*pulses)[2];  //pointer to a 2d array

} irPulseSet;

And to set the member you do the same:

upButton.pulses = upButtonPulses;

Or a more clever way to initialize the struct

irPulseSet upButton = { 31 , upButtonPulses } ;

Upvotes: 2

Related Questions