【问题标题】:C++, expression must be a modifiable lvalue [duplicate]C ++,表达式必须是可修改的左值[重复]
【发布时间】:2017-05-15 22:42:50
【问题描述】:

我有以下代码:

#include "stdafx.h"
#include<iostream>
using namespace std;

const int x = 5;
bool graf_adj[x][x] = {
0,1,1,1,0,
1,0,1,0,0,
1,1,0,1,1,
1,0,1,0,0,
0,0,1,0,0
};
struct Graf
{
    bool adj[x][x];
    char n;
};

int main(){
Graf graf1;
graf1.adj = graf_adj;
}

当我尝试将 graf_adj 分配给 graf1.adj 时,在主函数中 graf1.adj = graf_adj; 编译器给了我这个错误:

错误表达式必须是可修改的左值

谁能解决这个问题?

谢谢

【问题讨论】:

  • 您不能分配数组。您可以复制它们的内容,例如memcpystd::copy
  • 更好的是,使用标准数组或标准向量
  • 这个是否编译(x 没有类型)

标签: c++


【解决方案1】:

现在您已经添加了 const 的类型:

这里是使用 memcpy 的解决方案

#include<iostream>
#include <cstring>
const int x = 5;
bool graf_adj[x][x] = {
0,1,1,1,0,
1,0,1,0,0,
1,1,0,1,1,
1,0,1,0,0,
0,0,1,0,0
};
struct Graf
{
    bool adj[x][x];
    char n;
};

int main(){
Graf graf1;
std::memcpy(&graf1.adj, &graf_adj, sizeof(graf1.adj));
}

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2014-12-15
    • 2014-12-20
    • 2015-09-19
    • 2016-05-09
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多