0

So right after I do this swap function all the values in my array goes to -858993460. Why that number? I think it's the way I declare my array, but isn't A a pointer by declaring it that way? I'm trying to figure out why this is. well here's the code:

int* arrayCreate()//added mg
{
    int a[] = { 3, 7, 4, 9, 5, 2 };

    return a;
}

void Sort::Insert()
{   
    int t = 0;

    //start clock
    clock_t start = clock();
    d = arrayCreate();  
    size = 6;
    for (int i = 1; i< size; i++)
    {
        t = i;

        while (((t - 1) >= 0) && (d[t] < d[t- 1]))
        {
            //Swap
            Swap(d[t], d[t- 1]);  // right after this call 
                                  //the debugger says values go to - 8e^8
            t--;
        }
    }
}

void Sort::Swap(int& n1, int& n2)
{
    int temp = n1;
    n1 = n2;
    n2 = temp;
}
1
  • Doing some testing I realize if I do: int *a = new int[6]; a[0] = 3; a[1] = 7; a[2] = 4; a[3] = 9; a[4] = 5; a[5] = 2; This doesn't screw up the array after swap. But why? I am so curious I really must know. Commented Feb 21, 2015 at 6:13

1 Answer 1

2

You're overlooking that all stack based variables are destroyed once the scope they are defined in is exited.

therefore, as soon as you return A, it points to memory that is undefined.

int* arrayCreate()//added mg
{
    int a[] = { 3, 7, 4, 9, 5, 2 };

    return a;
}

Could be changed to this

int* arrayCreate()//added mg
{
    static int a[] = { 3, 7, 4, 9, 5, 2 };

    return a;
}

Marking the array as static will cause the memory to stick around.

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

4 Comments

It makes a lot of sense, but the values do stick around until swap in the debugger. Why is that?
Undefined is undefined. If you compile your code with a different compiler you will most likely get different results. Please know that when I say undefined I am not talking about the memory itself, but what the language says that data should be. It is implementation and compile dependent and the results will very. In CPP this is commonly referred to as undefined behavior.
I guess visual studios was throwing me off. I'll go with what you said. Also then is there an easier way to declare a predefined array pointer without using static?
You could always make it global (outside any functions).

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.