Cyclic shift Function without public parameters. Task: cyclic left shift

void zmischennya(int *masuv, int n,...) { int *mas,j,temp; mas=masuv; printf("\n Zmischennuy masuv:\n"); for (j=1; j<=n; j++) { *mas=*(mas+j); *(mas+n)=*(mas-(n-1)); printf("\t %i",*mas); } getch(); } 

I just can not display the last value, which was the first (or rather zero). What am I doing wrong ???

  • one
    Probably because the exchange of values ​​is not through a temporary variable. temp - unused !!! - gecube
  • 1. Why mas? 2. First index == 0 3. Shift by one position? How did @gecube write, where is temp? for (j = 0; j <n; j ++) {temp = masuv [j]; j1 = (j + 1)% n; masuv [j] = masuv [j1]; masuv [j1] = temp; } It is possible without temp (via "exclusive or") - alexlz
  • @ dark8eider, if you want to approach this issue seriously, you can familiarize yourself with the three algorithms of the cyclic shift of a one-dimensional array or string . - avp
  • one
    Damn, in a hurry did not take into account that temp should be assigned only once temp = masuv [0]; for (j = 1; j <n; j ++) masuv [j-1] = masuv [j]; masuv [n-1] = temp; - alexlz

1 answer 1

See it.

You have to write down the 1st element to the place of the 0th, then the 2nd to place the 1st, and so on. Then to the place of the last - 0th. So that this very 0th is not lost in the initial step, it should be saved into a temporary variable.

What are you doing? At the j step, you write the j element to the 0th place. That is, in a row, all the elements are written to zero. This is already wrong, right?

Then there is a complete disaster: *(mas-(n-1)) - this is the element with the index -(n-1) , that is, 1-n ! There is no such element in the array, that is, you fall into a random area of ​​memory. Then, *(mas+n) also wrong: in the n element array, the indices are from 0 to n-1 . Therefore, by the way, the cycle should be done not to n , but only to n-1 .

It became clearer?

  • Thank you very much. Finally, I understood everything. - dark8eider