无法在结构中返回指针数组

时间:2018-08-30 08:07:19

标签: c++11 visual-c++

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

2 个答案:

答案 0 :(得分:2)

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

int m[N];
strB.p=m;

第一个将m定义为 local 变量。因此,它将超出范围,并且其寿命将在函数返回后立即终止(变量m本质上将不复存在)。

第二行使strB.p指向此数组的第一元素。

这意味着当函数返回时,指针将立即变为无效,并且以任何方式使用它都会导致undefined behavior

自然的解决方案是使用std::arraystd::vector

template <int N>
struct strA{
    std::array<int, N> p;
};

template <int N>
strA<N> setValue(int n)
{
    strA<N> strB;
    for (int i=0; i<N;i++)
    {
        strB.p[i]=i+n;
    }
    return strB;
}

不需要临时数组。


当然,您也可以直接在结构中直接定义一个普通的C样式数组,仍然不需要像m这样的临时数组:

template <int N>
struct strA{
    int p[N];
};

答案 1 :(得分:1)

如果您在类似int m[n]的函数中声明一个数组,然后将其分配给一个指针,则该函数之后的该指针不会指向任何内容。您必须分配一个新区域并使用strB.p指针指向它,在 setValue

中执行此操作
strB.p=new Int[n]