C ++:将指针变量传递给函数 [英] C++: Passing pointer variable to function

查看:156
本文介绍了C ++:将指针变量传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类Node:

class Node {
public:
    int item;
    Node * nextLink;
};

在函数之外我声明一个Node指针:

Outside a function I declare a Node pointer:

Node * newNode;

然后,我将此指针传递给函数foo:

Then, I pass this pointer to a function foo:

void foo(Node * node) {

  node = new Node();

  node->item = 1;

  Node * anotherNode = new Node();

  anotherNode->item = 2;

  node->nextLink = anotherNode; 
}

实际呼叫:

foo(newNode);

在foo的末尾(但在现有之前),我可以看到node-> item和node- > nextLink指向正确的地方。但是,从foo返回时,我检查newNode,项目是正确的,但nextLink不存在。

At the end of foo (but before existing) I can see that node->item and node->nextLink point to the correct places. However, when returned from foo, I check newNode, and the item is correct, but the nextLink is not there.

有任何建议吗?
感谢

Any suggestions? Thanks

推荐答案

您需要传递参考。您正在修改指针的副本

You need to pass a reference. You are modifying a copy of the pointer

尝试

void foo(Node*& node) 

这篇关于C ++:将指针变量传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆