1

i am a beginner in c. i don't know that much how to use arrays as function parameters, arguments or how to return array from an function. to my knowledge, the below code should work fine. But i can't get where the problem is. the function is not working as it should.

//reversing an array using function
#include<stdio.h>
void rev(int array[],int length)
{
    int k,j,temp;
    for(k=length-1,j=0;k>=0&&j<length;k--,j++){
        temp=array[k];
        array[k]=array[j];
        array[j]=temp;
    }
}
int main()
{
    int c,arr[]={1,2,3,4,5,6,7,8,9};
    rev(arr,9);
    for(c=0;c<9;c++){
        printf("%d ",arr[c]);
    }
    return 0;
}
1
  • 1
    In fact you can't directly pass an array as a function argument, or return one as a function result. The parameter declaration int array[] really means int *array, a pointer (this applies only to parameter declarations). Suggested reading: section 6 of the comp.lang.c FAQ. Commented Aug 6, 2012 at 9:39

3 Answers 3

3

You only need to go until the middle of the array, if you go more, you re-reverse the array:

So this:

for(k=length-1,j=0;k>=0&&j<length;k--,j++){

Should be:

for(k=length-1,j=0;k > j;k--,j++){
Sign up to request clarification or add additional context in comments.

1 Comment

thanks very much. i just figured myself it just after posting it in the forum. thanks very much.
0

It looks to me like you're performing the reverse twice.

That is, you swap the beginning and end elements immediately, and at the end of your iteration you swap them again. i.e. you end up with the same array.

You can either:

  1. perform your swap only halfway through your array, or
  2. populate a second array in reverse from the first (I don't know if you want to repopulate the original array, however - you may need to copy it back in)

Comments

0

There no problem with array. Problem with your algo. //reversing an array using function

#include<stdio.h>
void rev(int array[],int length)
{
    int k,j,temp;
    for(k=length-1,j=0;k>=0 && j<length / 2; k--,j++){
        temp=array[k];
        array[k]=array[j];
        array[j]=temp;
    }
}

This reverse array. Your algo reverse it twice. So just add /2 in for conditions.

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.