c++ - 函数 C++ 中的动态分配

标签 c++ function dynamic-allocation

我在使用"new"和引用进行动态分配时遇到了一些麻烦。请看下面的简单代码。

#include<iostream>
using namespace std;
void allocer(int *pt, int *pt2);
int main()
{
    int num = 3;
    int num2 = 7;
    int *pt=&num;
    int *pt2 = &num2;
    allocer(pt, pt2);
    cout << "1. *pt= " << *pt << "   *pt2= " << *pt2 << endl;
    cout << "2. pt[0]= " << pt[0] << "   pt[1]= " << pt[1] << endl;

}


void allocer(int *pt, int *pt2)
{
    int temp;
    temp = *pt;
    pt = new int[2];
    pt[0] = *pt2;
    pt[1] = temp;
    cout << "3. pt[0]= " << pt[0] << "   pt[1]= " << pt[1] << endl;
}

我想要做的是让函数“allocer”获得 2 个参数,它们是 int 指针并在其中一个上分配内存。如您所见,*pt 变成了一个包含 2 个整数的数组。在函数内部它运行良好,这意味着我标记为 3 的句子按我的意图打印。但是,1、2 不起作用。 1 打印原始数据(*pt= 3, *pt2= 7),2 打印错误(*pt= 3, *pt2= -81203841)。 如何解决?

最佳答案

您正在传递 ptpt2按值的变量,所以任何新值 allocer分配给他们的任务保存在本地 allocer仅且不反射(reflect)回 main .

要执行您正在尝试的操作,您需要通过 pt通过引用(int* &pt)或通过指针(int** pt)使得allocer可以修改main中的变量正在被提及。

此外,没有充分理由通过 pt2作为指针,因为 allocer不将其用作指针,它仅取消引用 pt2得到实际的int , 所以你应该传入实际的 int而是按值。

尝试更像这样的东西:

#include <iostream>
using namespace std;

void allocer(int* &pt, int i2);

int main()
{
    int num = 3;
    int num2 = 7;
    int *pt = &num;
    int *pt2 = &num2;
    allocer(pt, *pt2);
    cout << "1. *pt= " << *pt << " *pt2= " << *pt2 << endl;
    cout << "2. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
    delete[] pt;
    return 0;
}

void allocer(int* &pt, int i2)
{
    int temp = *pt;
    pt = new int[2];
    pt[0] = i2;
    pt[1] = temp;
    cout << "3. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
}

或者

#include <iostream>
using namespace std;

void allocer(int** pt, int i2);

int main()
{
    int num = 3;
    int num2 = 7;
    int *pt = &num;
    int *pt2 = &num2;
    allocer(&pt, *pt2);
    cout << "1. *pt= " << *pt << " *pt2= " << *pt2 << endl;
    cout << "2. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
    delete[] pt;
    return 0;
}

void allocer(int** pt, int i2)
{
    int temp = **pt;
    *pt = new int[2];
    (*pt)[0] = i2;
    (*pt)[1] = temp;
    cout << "3. pt[0]= " << (*pt)[0] << " pt[1]= " << (*pt)[1] << endl;
}

关于c++ - 函数 C++ 中的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51757750/

相关文章:

c++ - C++中类对象属性的内存管理

java - JNI FindClass 导入失败

C++11 错误 - 当我尝试动态增加数组大小时,此错误意味着什么?

C++ 套接字客户端/服务器简单消息发送器

c++ - 为什么删除移动构造函数后我的对象没有被复制?

function - D 函数返回自动引用

c - 质量之间的引力

javascript - React Native setState 不是函数

c++ - 按值填充 std::vector 时,是否会删除动态分配的对象指针?

c++ - 在不破坏严格别名的情况下高效生成字节缓冲区