riverhare - 25 days ago 6

C++ Question

The problem I want to solve with next code is to rotate the integer array of some size to a certain number shift. For instance, for int a[5] = {1,2,3,4,5}, size =5 and shift = 2 the result must be {3,4,5,1,2}.

`void rotate(int a[], int size, int shift)`

{

for (int i = 0; i < shift%size; ++i) {

int *buffer = &a[0];

a = &a[1];

int l = *buffer;

a[size - 1] = l;

}

}

The output is right, but there is a runtime exception "Stack around the variable 'a' was corrupted". The problem is definitely in "a[size - 1] = l;", but I can't understand, what exactly is wrong.

Thanks in advance for your help.

Answer Source

`a = &a[1];`

is shifting the pointer `a`

by 1.

So `a[-1]`

to `a[3]`

inclusive are now the range of valid indices: `a[size - 1]`

violates that.

I'd advise against changing `a`

in this way.