结构成员在不同函数中的动态内存分配
dynamic memory allocation of struct member in different function
我想做一些像下面的代码片段:
using namespace std;
struct str {
int *integs;
};
void allocator(str*& str1) {str1.integs=new int[2];}
void destructor(str*& str1) {delete [] str1.integs;}
int main () {
str str1;
allocator(str1);
str1.integs[0]=4;
destructor(str1);
return 0;
}
然而,这不起作用;我得到错误:请求' str1 '中的成员' integer ',这是非类类型' str ' *
这是不可能的struct和我需要一个类吗?我必须使用->操作符吗?想法吗?
您将str1
作为对指针的引用。你的意思可能是:
void allocator(str& str1) {str1.integs=new int[2];}
void destructor(str& str1) {delete [] str1.integs;}
str1是指针的引用,应该使用
str1->integs
或仅用作参考:
void allocator(str& str1) {str1.integs=new int[2];}
void destructor(str& str1) {delete [] str1.integs;}
应该没问题
相关文章:
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- c++ 动态内存 堆栈中的分配
- 给定特定内存地址的数组的动态内存分配
- 释放动态内存时C++错误
- 我刚刚了解了C++中的动态内存分配
- 无法删除布尔动态内存分配
- 有没有办法找到动态内存大小,比如大小?
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 具有对齐存储的动态内存分配
- 指向数组unique_ptr在调用 release() 后会自动释放动态内存,这是真的吗?
- 在cpp中使用boost-python的python代码是否进行动态内存分配
- 我应该在这个程序中使用静态内存分配还是动态内存分配
- C++ 模板函数中的动态内存分配
- 指向动态内存中结构中的变量时出现问题
- C++具有动态内存分配的 constexpr 函数
- 动态内存分配错误
- 按引用传递和动态内存分配之间的区别是什么