0

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

2 Answers 2

2

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];
};
Sign up to request clarification or add additional context in comments.

Comments

1

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]

1 Comment

Dear helpers, thank you so much for the prompt replies. now my problem has been solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.