Runtime check failure #2

So I'm rotating an array to the left, and I actually got it to work correctly, but the problem is whenever I run it and input any number into k, I get a check failure, stack around variable 'a' was corrupted, although it does do the proper rotations, I think it has something to do with my a[i] = a[i+] since it technically goes out of bounds? Any thoughts on how to get rid of the error? I've tried fiddling with the size in my loop but it just messes up the output...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 #include <iostream>
using namespace std;

int main()
{
	int k; //rotations
	const int size = 8;
	int a[size]={22, 33, 44, 55, 66, 77, 88, 99};
	cout<<"How many times should the numbers be rotated? (1-7)"<<endl;
	cin>>k;
		
	cout<<"Original number set: \t";
	for(int o=0; o<size; o++)
	{
		cout<<a[o]<<" ";
	}
	cout<<endl;

	for(int rotate=1; rotate<=k; rotate++)
	{

	int temp= a[0];
	if (rotate==k)
	{
	cout<<"Rotated number set: \t";
	}
	for (int i=0; i<size; i++)
{
	a[i] = a[i+1];
	a[size] = temp;
	if (rotate==k)
	{
	cout<<a[i]<<" ";
	}
}
	}
	cout<<endl;
	return 0;
}
> I think it has something to do with my a[i] = a[i+] since it technically goes out of bounds?

Yes.
Also with a[size] = temp;, the position of the last element is size-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using namespace std;

int main()
{
    int k; //rotations
    const int size = 8;
    int a[size]= {22, 33, 44, 55, 66, 77, 88, 99};
    cout<<"How many times should the numbers be rotated? (1-7)"<<endl;
    cin>>k;

    cout<<"Original number set: \t";
    for(int o=0; o<size; o++) 
    {
        cout<<a[o]<<" ";
    }
    cout<<endl;

    for(int rotate=1; rotate<=k; rotate++)
    {

        int temp= a[0];
        // if (rotate==k)
        // {
            // cout<<"Rotated number set: \t";
        // }
        //for (int i=0; i<size; i++) // *****
        for (int i=0; i<size-1; i++) // *****
        {
            a[i] = a[i+1];
            // a[size] = temp; // *****
            // if (rotate==k)
            // {
            //    cout<<a[i]<<" ";
            //}
        }

        a[size-1] = temp ; // *****
    }
    // cout<<endl;
    //return 0;
    cout<<"Rotated number set: \t";
    for(int o=0; o<size; o++)
    {
        cout<<a[o]<<" ";
    }
    cout<<endl;

}



Thank you very much!
Topic archived. No new replies allowed.