等同指针值正在更改指针引用

Equating pointer value is changing pointer reference

本文关键字:指针 引用      更新时间:2023-10-16
struct node
{
    char *ptr = (char *)malloc(frames*sizeof(char));
}*start,*current;

然后我分配了等于 node 的内存来启动。

[...]//Assigned values to start node.
current = start;//Current points to start
node *temp = new node();//temp will point a newly created node
*temp = *current;//    COPYING VALUES OF CURRENT TO TEMP
[...]

我想创建一个新节点,temp指向它并将 current 的值(此处当前指向开始)复制到 temp。

但这会使临时点current(这里start)代替。沮丧。我哪里出错了?

*temp = *current应该temp = current .

可能有两种解决方案

  1. 将 *temp=*current 更改为 temp=current。这样做,您可以使用"temp"访问"current"的值,因为这两个指针现在引用相同的内存位置。警告,使用"当前"或"temp"更改值将导致两个指针中的值发生变化,因为它们引用相同的内存位置。
  2. 使用内存。它会将值从一个内存位置复制到另一个内存位置。这是参考。现在,您有两个独立的值副本。