0

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.)

3
  • 3
    If you were using standard library components (e.g. std::array), I think you wouldn't have a problem. Commented Sep 16, 2016 at 4:35
  • 2
    Do read on what static means. Commented Sep 16, 2016 at 4:39
  • 1
    S[i] = ReturnArray(a, b); means that you make S[i] point to the static array. It doesnt mean copy array contents. Commented Sep 16, 2016 at 4:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think my working example is waste because do the same work in twice
Thank you for your quick answer

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.