C++11 无法返回结构中的指针数组 我是C++新手。下面是我的代码。我在“setValue”中看到了正确的数组,但在“main”中,我无法在strC上获得正确的数组值。我错过了什么 template <int N> struct strA{ int *p; }; template <int N> strA<N> setValue(int n) { strA<N> strB; int m[N]; // pointer initialization strB.p=m; for (int i=0; i<N;i++) { strB.p[i]=i+n; } return strB; } int main(){ const int N=3; strA<N> strC; strC=setValue<N> (5); for (int i=0; i<N;i++) { cout<< strC.p[i]<<endl; } return 0; } 模板 strA结构{ int*p; }; 模板 斯特拉设定值(整数n) { strA strB; int m[N]; //指针初始化 strB.p=m; 对于(int i=0;i

C++11 无法返回结构中的指针数组 我是C++新手。下面是我的代码。我在“setValue”中看到了正确的数组,但在“main”中,我无法在strC上获得正确的数组值。我错过了什么 template <int N> struct strA{ int *p; }; template <int N> strA<N> setValue(int n) { strA<N> strB; int m[N]; // pointer initialization strB.p=m; for (int i=0; i<N;i++) { strB.p[i]=i+n; } return strB; } int main(){ const int N=3; strA<N> strC; strC=setValue<N> (5); for (int i=0; i<N;i++) { cout<< strC.p[i]<<endl; } return 0; } 模板 strA结构{ int*p; }; 模板 斯特拉设定值(整数n) { strA strB; int m[N]; //指针初始化 strB.p=m; 对于(int i=0;i,c++11,visual-c++,C++11,Visual C++,,setValue函数中的这两行是问题: int m[N]; strB.p=m; 第一个定义为m的局部变量。因此,它将超出范围,其生命周期将在函数返回时结束(变量m基本上不再存在) 第二行makestrB.p指向该数组的第一个元素 这意味着当函数返回指针时,指针将立即失效,以任何方式使用它都会导致错误 自然解决方案是使用或: setValue函数中的这两行是问题所在: int m[N]; strB.p=m; 第一个定义为m的局部变量。因此,它将超出范围,其生命周期将在函数返回时结束(变量m基

setValue
函数中的这两行是问题:

int m[N];
strB.p=m;
第一个定义为
m
局部变量。因此,它将超出范围,其生命周期将在函数返回时结束(变量
m
基本上不再存在)

第二行make
strB.p
指向该数组的第一个元素

这意味着当函数返回指针时,指针将立即失效,以任何方式使用它都会导致错误

自然解决方案是使用或:


setValue
函数中的这两行是问题所在:

int m[N];
strB.p=m;
第一个定义为
m
局部变量。因此,它将超出范围,其生命周期将在函数返回时结束(变量
m
基本上不再存在)

第二行make
strB.p
指向该数组的第一个元素

这意味着当函数返回指针时,指针将立即失效,以任何方式使用它都会导致错误

自然解决方案是使用或:


如果在
int m[n]
之类的函数中声明一个数组,然后将其分配给指针,则函数后面的指针不会指向空。您必须分配一个新区域并用strB.p指针指向它,请在setValue中执行此操作

strB.p=new Int[n]

如果在
int m[n]
之类的函数中声明一个数组,然后将其分配给指针,则函数后面的指针不会指向空。您必须分配一个新区域并用strB.p指针指向它,请在setValue中执行此操作

strB.p=new Int[n]

欢迎来到stackoverflow.com。请花点时间阅读,阅读,阅读欢迎来到stackoverflow.com。请花点时间阅读,阅读,阅读亲爱的助手们,非常感谢你们的及时回复。现在我的问题已经解决了。亲爱的助手们,非常感谢你们的及时回复。现在我的问题已经解决了。