0

I am trying to reverse the array.

#include<stdio.h>
//code to reverse the current array1
void reverse(int array1[]){
    int i;
    int n=3;
    for  (i = 0; i <n; i++)
    {
        array1[i]=array1[n-i-1];
        printf("%d\t",array1[i]);
    }

}

int main(){
    int array1[]={1,2,3};
     reverse(array1);
}
result 3 2 3

when i compile this code i am getting 3 in array[0] poistion what is my error?

1
  • 1
    This would be a great problem for using a Debugger. Step through each line of code, and watch the array change at each step. Then the error will be obvious. Commented May 4, 2020 at 13:29

2 Answers 2

1

You are reading and writing the same array, so some writing will break data that are not read yet.

Typical way to reverse is to swapping elements in former half and latter half.

void reverse(int array1[]){
    int i;
    int n=3;
    for  (i = 0; i <n; i++)
    {
        if (i < n-i-1) /* avoid swapping the same pair twice */
        {
            int tmp=array1[i];
            array1[i]=array1[n-i-1];
            array1[n-i-1]=tmp;
        }
        printf("%d\t",array1[i]);
    }

}
Sign up to request clarification or add additional context in comments.

Comments

0

Can't write code right now.

You're overwriting array's value at position 0 on the first loop, so when your code checks the value at position 0 it reads the new value instead of the old one).

Create a second array to write the inverted values instead of overwriting them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.