user10293779
user10293779

Reputation: 103

Can not return pointer array in the struct

I am new to C++. below is my code. I saw a correct array in "setValue", but in "main", I can not get the right array value on strC. where did I miss?

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

Upvotes: 0

Views: 58

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409216

These two lines in the setValue function is the problem:

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

The first defined m as a local variable. As such it will go out of scope and its lifetime will end as soon as the function returns (the variable m will in essence cease to exist).

The second line make strB.p point to the first elements of this array.

That means when the function returns the pointer will immediately become invalid, and using it in any way will lead to undefined behavior.

The natural solution is to either use std::array or std::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;
}

No temporary array needed.


Of course, you could just define a normal C-style array directly in the structure as well, and still no temporary array like m being needed:

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

Upvotes: 2

Andrea Bellizzi
Andrea Bellizzi

Reputation: 497

If you declare an array in a function like int m[n] and then assign it to a pointer, this pointer after the function doesn’t point to nothing. You have to allocate a new area and point it with the strB.p pointer, do this in setValue

strB.p=new Int[n]

Upvotes: 1

Related Questions