结构成员在不同函数中的动态内存分配

dynamic memory allocation of struct member in different function

本文关键字:动态 内存 分配 函数 成员 结构      更新时间:2023-10-16

我想做一些像下面的代码片段:

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;}

应该没问题