错误: 要求L值作为赋值运算符的左操作数(第4行)
请帮助我理解,我哪里出了错以及为什么会发生这个错误?
int *x = nullptr;
x = (int*) realloc(x, 10);
for (int i = 0; i < 10; ++i) {
(x + i) = new int(i + 3);
}
(x + i) = new int(i + 3);
应该是
*(x + i) = i + 3;
(x + i)
会产生一个指针rvalue (const int*
),不能被赋值,但可以通过合法的解引用*(x + i)
。
通常情况下,你应该避免在c++代码中手动管理内存(尤其是不使用realloc()
)。
你可以按照以下方式重写你的c++代码片段:
std::vector<int> x(10);
int i = 0;
for (auto& elem : x) {
elem = i + 3;
++i;
}
(x + i) = new int(i + 3);
*(x + i) = i + 3;
123 = 456;
。 - P.W
x
has typeint*
, sox+i
also has typeint*
. Type-wise, your code checks out. However, it does not make sense semantically:x+i
is the address of someint
, and you are trying to assign a new address (int*
) to it. The correct syntax is*(x + i) = i+3
orx[i] = i+3
- Botjex
实际上是什么。 - πάντα ῥεῖint x = 0; int i = 1; (x + i) = 3;
相同的情况,你不应该期望它能够工作。(关于指针最重要的一点是,指针本身并没有什么特别之处。) - molbdnilo