Reputation: 117
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;
}
Upvotes: 0
Views: 114
Reputation: 2279
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.
Upvotes: 2