函数C++中的动态分配

Dynamic allocation in function C++

本文关键字:动态分配 C++ 函数      更新时间:2023-10-16

我在使用"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的本地,而不会反映回main

要执行您正在尝试的操作,您需要通过引用(int* &pt(或指针(int** pt(传递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;
}

你刚才做的是动态分配函数内部的 pt。并且这个函数变量 pt 是局部的,与主函数中的 pt 不一样。 您可以做的是,如果要将内存动态分配给指针,则可以传递指针本身的地址。