无法将指针的值更改为等于另一个指针

Can't change the value of a pointer to equal another pointer

本文关键字:指针 另一个      更新时间:2023-10-16

我将团队作为团队对象的数组,而matches是团队对象中Match对象的数组。thisMatch声明为:

Match* thisMatch = new Match();

这就是我要做的:

&(teams[i].matches[foundMatches]) = thisMatch;
// I also tried another method:
(tams[i].matches + foundMatches) = thisMatch;

其中foundMatches是内部

然而,无论我做什么,我都会不断地得到这个编译器错误:

error: lvalue required as left operand of assignment
                 &teams[i].matches[foundMatches] = thisMatch;
                                                 ^

有人知道可能出了什么问题吗?如果需要,我可以提供更多信息,但我认为大部分信息都不相关。

您要做的是将变量分配给常数值。teams[i].matches[foundMatches]的地址已经预定义(在声明数组时),不能更改。

您要做的是更改teams[i].matches[foundMatches]的内容(更进一步,我假设这是一个Match对象,因为您说过matches是Team对象中的Match对象数组)。改变内容可以通过teams[i].matches[foundMatches] = *thisMatch来完成,即将thisMath的内容(即*thisMath)分配给数组条目。

除非您在之前或之后没有使用thisMath进行任何无法直接对teams[i].matches[foundMatches]执行的操作,否则您可以使用teams[i].matches[foundMatches] = Match()并实例化对象,而不是分配内存并将其复制到teams[i].matches[foundMatches],从而强制词尾释放。

注意:请确保在Match类中实现了一个CTOR/CCTOR,因为副本将涉及其中任何一个。

teams[i].matches[foundMatches] = thisMatch;

如果假设matches包含指向匹配项的指针数组,则应该声明它:

Match **matches;

然后您应该将其分配为:

team[i].matches = new (Match*)[num];

然后以上作业就可以了。