Program keeps crashing. I'm assuming it's because the pointer is pointing out of bounds when I try to deallocate the memory, but I'm not so sure if that really is the problem. Any idea?
#include <iostream>
using namespace std;
int main()
{
const int sze = 3;
int *ptr1 = new int[sze];
for (int i = 0; i < sze; i++)
{
cout << "Enter a number: ";
cin >> *(ptr1); // take the current address and place input to it
cout << ptr1 << "\n"; // just to check the address
ptr1++ ; // traverse the array
/* // remove this and the program will crash
// re-aim the pointer to the first index
if(i == 2)
{
ptr1-=3;
}
// alternative ptr1 = nullptr;
*/
}
delete [] ptr1;
You are advancing the pointer that new[]
returns. You really should not be doing that at all. You need to pass delete[]
the same address that new[]
allocates. As your commented out code says, you would need to decrement the pointer back to its original value to avoid the crash.
You should use another pointer to iterate your array, eg:
#include <iostream>
using namespace std;
int main()
{
const int sze = 3;
int *ptr1 = new int[sze];
int *ptr2 = ptr1;
for (int i = 0; i < sze; i++)
{
cout << "Enter a number: ";
cin >> *ptr2; // take the current address and place input to it
cout << ptr2 << "\n"; // just to check the address
ptr2++ ; // traverse the array
}
delete [] ptr1;
}
Or, iterate the array using the index already provided by your loop counter, eg:
#include <iostream>
using namespace std;
int main()
{
const int sze = 3;
int *ptr1 = new int[sze];
for (int i = 0; i < sze; i++)
{
cout << "Enter a number: ";
cin >> ptr1[i]; // take the current address and place input to it
cout << ptr1[i] << "\n"; // just to check the address
}
delete [] ptr1;
}