arrayscstructlvalue

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


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.


Solution

  • 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;