Reputation: 458
I am having an issue with outputting an array. When I output each element without a for
loop, the program runs fine. When I try to output with a for
loop, the program crashes the first time I set an element in the array. I have marked the line where the program crashes when I uncomment out the for
loop. My sort seems to work fine and the program is crashing way before that, so I'm pretty sure that isn't the issue. Any ideas why the 2nd for
loop would crash the program at the specified line?
int main()
{
int* Array;
int j = 5;
for(int i=0; i<5; i++)
{
Array[i] = j; //Crashes here with 2nd for loop uncommented
cout << Array[i] << endl;
j--;
}
Array = insertion_sort(Array);
cout << Array[0] << endl;
cout << Array[1] << endl;
cout << Array[2] << endl;
cout << Array[3] << endl;
cout << Array[4] << endl;
/*for(int k=0; k <5; k++)
{
cout << Array[k] << endl;
}*/
}
Upvotes: 1
Views: 105
Reputation: 4437
You are accessing the pointer before initializing it. You should change
int* Array;
to
int* Array = new int[5]; // There are 5 ints in my array
and make sure to
delete[] Array;
at the end, or even better:
int Array[5]; // This way you don't need the new keyword, so you won't need to delete[] later
Upvotes: 3
Reputation: 390
Right now, your array is not instanciated. It's just a pointer. You need to choose how large of an array you want before you can start writing to it.
int* Array = new int[5];
int j = 5;
for(int i=0; i<5; i++)
{
Array[i] = j; //Crashes here with 2nd for loop uncommented
cout << Array[i] << endl;
j--;
}
Upvotes: 1