-2

I don't know what is happening in this program, I am modifying an array of 6 elements with this function, which is supposed to swap the elements in this way:

ex array[6]={1,2,3,4,5,6};

output:

3 2 1 6 5 4

But instead, I am getting:

output:

3 2 1 4 5 6

Could you tell me what I am doing wrong please?

the function:


void invert (int *buf){
int i,j,swap; 

for (i = 0 ; i < ( 3 - 1 ); i++)
  {
    for (j = 0 ; j < 3 - i - 1; j++)
    {
        swap       = buf[j];
        buf[j]   = buf[j+1];
        buf[j+1] = swap;
    }
  }

for (i =3  ; i < (6 - 1); i++)
  {
    for (j = 3 ; j < 6 - i - 1; j++)
    {
        swap     = buf[j];
        buf[j]   = buf[j+1];
        buf[j+1] = swap;
    }
  }
} 

I called in the main like this:

main ( int argc , char * argv [])
{
int k;
int array[6]={1,2,3,4,5,6};
invert(array);
for(k=0;k<6;k++)
    {
        printf("%d ",array[k]);
    }
printf("\n");
}

I apreciate your help

lurker
  • 56,987
  • 9
  • 69
  • 103
chang
  • 1
  • 1
  • 4
    The debugger will tell you the answer. – Eugene Sh. Jan 12 '18 at 17:54
  • 1
    https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ https://stackoverflow.com/questions/2069367/how-to-debug-using-gdb – Yunnosch Jan 12 '18 at 17:55
  • I am compiling with "gcc -o program program.c -lm" and there is no error neither warnings, could you write how the code should looks like? – chang Jan 12 '18 at 18:02

1 Answers1

1

Fix

The last for loop is out of order. When you assign int i = 3 the second for loop inside will never run as 3 < 6-3-1 is false. Copy the outer loop from above:

for (int i = 0; i < 2; i++)
{
    for (j = 3 ; j < 6 - i - 1; j++)
    {
        swap     = buf[j];
        buf[j]   = buf[j+1];
        buf[j+1] = swap;
    }
}

This will produce 3 2 1 6 5 4.

Proposal:

I might add: you could implement the method in a better way even.

void invert (int *buf, int len){
    for(int i = 0; i < len/2; i++){
        int temp = buf[i];
        buf[i] = buf[len-i-1];
        buf[len-i-1] = temp;
    }
}

The above inverts a buffer quite cleanly. It's called so:

int main(){
    int k;
    int a[6] = {1,2,3,4,5,6};
    invert(a,3);
    invert(a+3, 3);
    for(k=0;k<6;k++)
        {
            printf("%d ",a[k]);
        }
    printf("\n");
    return 0;
}

Don't always settle for the first thing that comes to mind ;)

Community
  • 1
  • 1
Felix
  • 2,548
  • 19
  • 48