#include <QCoreApplication>
#include <QDebug>
void func1(int *pCnt)
{
pCnt = new int(1);
}
void func2(int* &pCnt)
{
pCnt = new int(2);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int *pCnt1 = nullptr;
func1(pCnt1);
if(nullptr != pCnt1)
qDebug() << "*pCnt1: " << *pCnt1;
else
qDebug() << "pCnt1 nullptr"; // 输出这句
int *pCnt2 = nullptr;
func2(pCnt2);
if(nullptr != pCnt2)
qDebug() << "*pCnt2: " << *pCnt2; // 输出这句
else
qDebug() << "pCnt2 nullptr";
return a.exec();
}
// 运行结果:
pCnt1 nullptr
*pCnt2: 2
C++指针与内存管理
该篇博客探讨了C++中void指针的使用,通过func1和func2两个函数展示了指针传递的不同方式。在func1中,指针pCnt1未成功分配内存,因此在main函数中输出为nullptr。而在func2中,使用了引用传递,成功为指针pCnt2分配了内存,输出显示为2。博客揭示了C++中指针和内存管理的细节及其重要性。
1379

被折叠的 条评论
为什么被折叠?



