我在使用"new"和引用进行动态分配时遇到了一些麻烦。请看下面的简单代码。
#include<iostream>
using namespace std;
void allocer(int *pt, int *pt2);
int main()
{
int num = 3;
int num2 = 7;
int *pt=#
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)。 如何解决?
最佳答案
您正在传递 pt
和 pt2
按值的变量,所以任何新值 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 = #
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 = #
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/