expression must be a modifiable lvalue C/C++(137)

129 views Asked by At

I am trying to assign an 2D array to another 2D array that is defined in a struct. But I get this error; 'expression must be a modifiable lvalue C/C++(137)'.

Here is the code;

#define NUM_TEMPLATES 4

float templateForehand1[3][50];
struct templ_st {
    float frame[3][50];
};
struct templ_st templates[NUM_TEMPLATES];

templates[0].frame = templateForehand1;

I am getting the error for the last line.

Any insight for why this error happens will be appreciated.

2

There are 2 answers

0
0___________ On BEST ANSWER

You cannot assign arrays in C language.

You need to copy it or use pointer.

    memcpy(templates[0].frame, templateForehand1, sizeof(templates[0].frame));

or

struct templ_st {
    float (*frame)[50];
};

/* ... */

templates[0].frame = templateForehand1;

But the 2nd option will not provide a deep copy of the array only reference to it.

Another option is to use structs as both objects

struct templ_st {
    float frame[3][50];
};

struct templ_st templateForehand1 ={{ /* init */ }};

/*   ... */
    struct templ_st templates[NUM_TEMPLATES];

    templates[0].frame = templateForehand1;

0
Lundin On

You can assign a struct containing an array to another struct of the same type. However, C doesn't allow assignment/initialization of raw arrays - it's just how the language was designed.

Option 1 - use structs only:

struct templ_st {
    float frame[3][50];
};

const struct templ_st template1 = { .frame = {/* array init list here */} };
struct templ_st templates[NUM_TEMPLATES];
...
templates[0] = template1;

Option 2 - memcpy:

memcpy(templates[0].frame, templateForehand1, sizeof(templates[0].frame));