I'm working on a rather big program. Everything works fine:) , until I added this simple code:

int counter_x = 0;
int* x = new int;

for (int a = 1; a < plain_len; a++)          //plain_len: int
{
     int b = a;
     while ( b != 0 )
     {
          x[counter_x] = b;
          cout << x[counter_x] << " ";
          counter_x++;
          b--;
     }
     cout << endl;
}

Run: (this time plain_len = 11)

1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6


Then: "Access violation reading location 0x00000021." comes up!
:(

What's wrong?
As I wrote before, this loop works a while, then the error occur.
Why?

Your array is too small, you only allocated space for only one int element.

int* x = new int;
correct way: int* x = new int [ the amount you need ];
while ( b != 0 )
{
          x[counter_x] = b;
          cout << x[counter_x] << " ";
          counter_x++;
          b--;
}

In your loop you index out of your array. The program is trying to access areas of the memory, which don't belong to it, and thats why you got that memory access violation error.

This question has already been answered. Start a new discussion instead.