函数C++中的动态分配
Dynamic allocation in function C++
我在使用"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
的本地,而不会反映回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 = #
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;
}
你刚才做的是动态分配函数内部的 pt。并且这个函数变量 pt 是局部的,与主函数中的 pt 不一样。 您可以做的是,如果要将内存动态分配给指针,则可以传递指针本身的地址。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问动态分配列表中的元素
- 为什么 std::equal_to会导致动态分配?
- 调用析构函数以释放动态分配的内存
- 动态分配Q_Property变量
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 使用动态分配将 char* 复制到另一个字符**
- 使用指针在存在特征库的情况下动态分配 c++ 中的矩阵
- 二维阵列的动态分配
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 在运行时为动态分配的内存输入值
- 释放动态分配的内存时是否需要执行此额外步骤
- 动态分配字符数组的内存