JoC
JoC

Reputation: 253

Reverse array in C?

Hi guys I just cant seem to reverse my array, my syntax looks ok and my logic seems fine but the FOR function is just not iterating through. This function is meant to reverse arrays, mainly strings. and n = length of the string.

#include <stdio.h>
#include <string.h>

void reverse(char, int);

int main()
{
    char a[100];
    gets(a);

    reverse(a, strlen(a)-1);

    printf("%s\n",a);
    getchar();
    getchar();
    getchar();
    return 0;
}

void reverse(char ar[], int n)
{
    char c;
    int i = 0;
    printf("n = %d" , n);
    for ( i = 0; i >= n ; i++){
        c = ar[i];
        ar[i] = ar[n];
        ar[n] = c;
        printf("Processed");
        n--;}

}


/*
if (begin >= n)
return;

c          = *(x+begin);
*(x+begin) = *(x+n);
*(x+n)   = c;
offs = x++;
printf("Begin = %d   ,  n = %d, offs = %p  \n", begin, n, offs);
reverse(x, ++begin, --n); */

Upvotes: 0

Views: 387

Answers (3)

Maurizio Ricci
Maurizio Ricci

Reputation: 472

This is O(N) performance. Actually you only perform N/2 iterations

void reverseArray(char[] arr) {
        int start = 0, end = strlen(arr) - 1, tempVal;
        for (; start < end; start++, end--) {
            //swap start & end location
            tempVal = arr[end];
            arr[end] = arr[start];
            arr[start] = tempVal;
        }
    }

Upvotes: 0

Paul R
Paul R

Reputation: 212949

As well as the logic bug already pointed out by @H2CO3, your function prototype is wrong - change:

void reverse(char, int);

to:

void reverse(char *, int);
             ^^^^^^

Note that if you compile with warnings enabled (e.g. gcc -Wall ...) the compiler will point out such mistakes and thereby save you a lot of time and effort.

Upvotes: 2

user529758
user529758

Reputation:

The condition with the loop variable is wrong, it should test for less-than, not for greater-than (since you seem to want to go from 0 to n).

i >= n should be i < n / 2.

Upvotes: 3

Related Questions