c++ - 返回空指针

标签 c++ pointers

我有一个定义如下的测试:

ClassName FileHandle;
ClassName1* data; //I want function to define this later

FileHandle.getData(data); //this is null after the call but isn't in function it calls
                          //why isn't the pointer defined from the method called? How fix?

它调用的函数如下所示:

void ClassName::getData(ClassName1* data)
{
    char * buf = "lots of data";        
    data = new ClassName1(buf, sizeof(buf)); //it's in there
}

我确信这是我对指针和引用的理解的问题。你知道我在这里做错了什么吗?为什么当数据返回到我的测试时,数据的值仍未定义?

我看到了指针和函数调用的示例 here但我很难找到这样的例子。 This看起来也可能很相似,但我还是很困惑。

最佳答案

通过引用传递指针本身&:

void ClassName::getData(ClassName1* &data2)

为了清楚起见,我将变量重命名为 data1data2,以便您可以看到它们是不同的。只有当通过引用传递时,它们实际上是相同的,否则在 getData 函数退出后,存储在本地指针 data2 中的地址将被销毁,并且原始存储在输入中的 NULL 地址data1 保持不变。

调用语法保持不变:

FileHandle.getData(data1);

关于c++ - 返回空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896105/

相关文章:

pointers - 将结构指针转换为接口(interface){}

c++ - C++ 中的函数指针和未知数量的参数

c++ - 'std::cout' 声明中的明确资格

c - 将指向 char 数组的指针传递给函数

c - 解决错误 "return makes pointer from integer without a cast"

c++ - 通过指针在 C++ 中的 char array[] 中小写大写字母

c++ - 如何从 Visual Studio 2017 社区版 C++ 项目导出 DLL?

c++ - 如何在不收到编译器警告的情况下使用 C++ 枚举

c++ - 有没有办法用静态 OpenSSL 构建静态 Qt?

c - 获取数组的长度