adding an element to the end of an array

Hello all,

I want to thank anyone in advance for taking the time to look at my post.That said, I want to add a number to slot 5th in an array.

This is what I tried, and I got "Run-Tume check failure #2 - stack around the variable "array1" was corrupted".

1
2
3
4
5
6
7
8
9
10
11
12
13
int array1[5]

num = 0;
num2 = -1;

for(int i = 0; i < 5; i++)
{
  cout<< "Enter a number: ";
  cin  >> array[num];
}

array1[5] = num2


Thanks again
You have declared an array of length 5. This allocates memory for 5 spaces in the array which in your case would mean that array1[4] is the end of the array and array1[0] is the start (0, 1, 2, 3, 4 gives you 5 spaces).

Any attempt to access past the arrays end will cause errors like the one your are experiencing.

So if you want to put a value in your array at 'array1[5]' you would need to declare the array using 'int array1[6]'. Try this...

1
2
3
4
5
6
7
8
9
10
11
12
int array1[6]

num = 0;
num2 = -1;

for(int i = 0; i < 5; i++)
{
  cout<< "Enter a number: ";
  cin  >> array[num];
}

array1[5] = num2


Last edited on
That worked, thank you
Topic archived. No new replies allowed.