fantoro fantoro -3 years ago 146
C++ Question

"Project.exe has triggered a breakpoint" after p_array++; in Visual Studio 2015

So I tried to learn pointers again and when I entered a number Visual Studio gave me an error.
Here's the source:

// Includes
#include "stdafx.h"
#include <iostream>
#include <conio.h>

using namespace std;

// Variables
int amount;

// Main function
int main()
{
cout << "How many numbers should be in this array: ";
cin >> amount;
int *p_array;
p_array = new int[amount];
for (int i = 0; i < amount; i++)
{
cout << (int)p_array << endl;
p_array++;
}
delete[] p_array;
_getch();
return 0;
}


I know that there's a problem with
p_array++;
.

Also when I tried to compile this in Code::Blocks it worked perfectly (I deleted
#include "stadfx.h"
and changed
_getch();
to
getch();
when compiling it in codeblocks).

P.S. I'm new to C++ :P

Answer Source

I fixed it by doing this:

// Includes
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>

using namespace std;

// Variables
int amount;
int *pointer;

// Main function
int main()
{
    cout << "How many numbers should be in this array: ";
    cin >> amount;
    int *p_array;
    p_array = new int[amount];
    pointer = p_array;
    for (int i = 0; i < amount; i++)
    {
        cout << (int)p_array << endl;
        p_array++;
    }
    p_array = pointer;
    delete[] p_array;
    _getch();
    return 0;
}

I made a pointer with name pointer and stored original address of p_array then before delete[] p_array; i assigned address stored in pointer to p_array.

Thanks to drescherjm for telling me what's the problem.

I guess that noone will need this explanation but I thought to write it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download