表达式必须是可修改的左值C/C++(137)[重复]

mwecs4sa  于 7个月前  发布在  C/C++
关注(0)|答案(2)|浏览(167)

此问题在此处已有答案

Why do C and C++ support memberwise assignment of arrays within structs, but not generally?(5个答案)
Assign the static array to another array(3个答案)
7天前关闭
我试图将一个2D数组分配给另一个在结构中定义的2D数组。但我得到了这个错误; 'expression must be a modifiable lvalue C/C++(137'。
这里是代码;

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

字符串
我得到了最后一行的错误。
任何关于为什么会发生这种错误的见解都将受到赞赏。

nwlls2ji

nwlls2ji1#

在C语言中不能赋值数组。
你需要复制它或使用指针。

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

字符串

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

/* ... */

templates[0].frame = templateForehand1;


但是第二个选项不会提供数组的深度副本,只提供对它的引用。
另一种选择是使用结构作为两个对象

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

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

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

    templates[0].frame = templateForehand1;

l3zydbqr

l3zydbqr2#

你可以将一个包含数组的结构体赋值给另一个相同类型的结构体。然而,C不允许原始数组的赋值/初始化-这只是语言的设计方式。
选项1 -仅使用结构:

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;

字符串
选项2 -memcpy

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

相关问题