Shifting a 2D array to the right

Thread Starter

Dritech

Joined Sep 21, 2011
901
Hi,
I am trying to shift a 2D array (with variable width) to the right.
My first attempt was the code below. This did not work since I was filling all elements with the values of the first column.

C:
for(i = 0; i < array_width-1; i++)
{
     for(j = 0; j < 5; j++)       
     {
           ADC_process[j][i+1] = ADC_process[j][i];  // shift all columns to the right by one
     }
}

Is the code below the correct way to implement this?
The first column will not be changed, but that is ok for my application.

C:
for(i = array_width-1; i == 0; i--)
{
    for(j = 0; j < 5; j++)
    {
         ADC_process[j][i] = ADC_process[j][i-1];
    }
}
 

WBahn

Joined Mar 31, 2012
29,976
Bench check (i.e., walk through it by hand with a pencil and paper) your original code and you will see why it behaves as it does. To make the bench check easy, start with an array_width of three or four.

Then bench check your final code and you will see why it starts to behaves like you want, with two problems.

The first problem is that your outer loop only stays in the loop if 'i' is exactly equal to zero. So unless the array_width is equal to 1, the outer loop will never execute at all.

Try changing your test to 0 < i.

Second (and it's hard to tell if your approach will have this problem since your test for the outer loop is incorrect), you (pretty much) never want to try to access an array element outside of the array bounds. C will be more than happy to let you do this -- but there be demons in those waters. So you need to make sure that your index values are never less than zero (or greater than or equal to the array length).
 

WBahn

Joined Mar 31, 2012
29,976
Loops in general, but mostly nested for-loops.
If while() loops become non-confusing, it can help to remember that a for() loop is nothing more than syntactic sugar for a while loop in which the first statement is placed before the while() loop, the second statement is the while() loop test expression, and the last statement is placed at the end of the while() loop's body.

For nested loops, just remember that the inner loops is just a loop. Nothing special about it. Like any loop, it has access to the value of those variables outside the loop that are in scope. Some of those just happen to be values that have been set by the present iteration of the outer loop.
 
Top