【问题标题】:Equating pointer value is changing pointer reference相等的指针值正在改变指针引用
【发布时间】:2014-02-19 13:35:39
【问题描述】:
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)。 沮丧的。我哪里错了?

【问题讨论】:

  • 这是什么语言?当然不是 C ...
  • 在 c++ 中做,但我看不出有任何理由让它不在 c 中运行
  • @SrujanBarai 你知道C 中没有new,对吧?而且你不能在这样的结构声明中调用函数?不确定你是否可以在 C++ 中做到这一点。
  • 结构中的函数调用是工作伙伴。 c++

标签: c++ pointers struct nodes


【解决方案1】:

*temp = *current 应该是temp = current

【讨论】:

  • 这将使temp 指向current 不是吗?我想添加它的值
  • 宁可让temp 指向current 指向的位置。我的坏
【解决方案2】:

可能有两种解决方案

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

【讨论】:

  • 我正在寻找的东西。
猜你喜欢
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
  • 2017-08-01
相关资源
最近更新 更多