JongHyeon Yeo
JongHyeon Yeo

Reputation: 1009

How to return C++ Array Pointer in method

First, I made funciton that return Array[2]'s pointer.

int* ReturnArray(int a, int b) {
    static int Array[2];


    Array[0] = a;
    Array[1] = b;

    return Array;
}

And I made simple 2-Dimensional array in Main.

int a, b;
in >> NumberOfSize;
int** S = new int*[NumberOfSize];
for (int i = 0; i < NumberOfSize; i++)
    S[i] = new int[2];

Last, I added ReturnArray(a,b) to set the value of S[i]

for (int i = 0; i < NumberOfSize; i++)
{
    in >> a >> b;
    S[i] = ReturnArray(a, b);
}

But in Main, I cannot get right value in Array S[i][j]. When I changed upper way to under, I can set the right value in array S.

for (int i = 0; i < NumberOfSize; i++)
{
    in >> a >> b;
    S[i][0] = ReturnArray(a, b)[0];
    S[i][1] = ReturnArray(a, b)[1];
}

What happended in upper way?

And How can i get right value in only one call ReturnArray function?

(sorry for my fool english.)

Upvotes: 0

Views: 249

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

The problem it's that you have a static local variable in the function, that means all calls to the function will share the same array and modify the same array, which means only the values set in the last call will be the ones you use.

One way to solve the problem is to do your dynamic allocation and copy the values separately like you do in your working example. Another possible solution is to use another data structure with proper copy-semantics, like e.g. std::pair or std::tuple, and don't have any static array (or anything static at all) in the function.

Upvotes: 1

Related Questions