【问题标题】:Dynamic allocation in function C++函数 C++ 中的动态分配
【发布时间】:2018-08-09 01:45:05
【问题描述】:

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

#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)。 如何解决?

【问题讨论】:

标签: c++ function dynamic-allocation


【解决方案1】:

您正在按值传递ptpt2 变量,因此allocer 分配给它们的任何新值仅保留在allocer 的本地,而不会反映回main

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

【讨论】:

    【解决方案2】:

    您刚刚所做的是动态分配了函数内部的 pt。而且这个函数变量pt是局部的,和main函数中的pt是不一样的。 您可以做的是,如果您想为该指针动态分配内存,您可以传递指针本身的地址。

    【讨论】:

      猜你喜欢
      • 2013-10-31
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2014-08-19
      相关资源
      最近更新 更多