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

C++ 不同函数中结构成员的动态内存分配,c++,struct,dynamic-memory-allocation,C++,Struct,Dynamic Memory Allocation,我想做一些类似以下代码片段的事情: 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.in

我想做一些类似以下代码片段的事情:

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”中的成员“integs”请求,该成员为非类类型“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;}

通过指针访问对象并使用点(
)操作符应该没问题。使用
->
代替,或者通过引用获取参数(
str&
代替
str*&
)@jorgen:为了更清楚地理解引用: