等于指针值正在改变指针引用

时间:2014-02-19 13:35:39

标签: c++ pointers struct nodes

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(此处当前指向start)的值复制到temp。

但这是临时点current(此处为start)。 失意。我哪里错了?

2 个答案:

答案 0 :(得分:2)

*temp = *current应为temp = current

答案 1 :(得分:0)

可能有两种解决方案

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