How do you reverse an array?

Printable View

- 03-29-2007ducksickiiHow do you reverse an array?
How do you reverse an array?

- 03-29-2007vart
search forum for reverse string assignments

- 03-29-2007robatino
Assuming that the array a is a general type of array for which you know the length n, then exchange

a[0] with a[n-1]

a[1] with a[n-2]

etc. If the truncated value of (n-1)/2 is N, then the last exchange is a[N] with a[n-1-N] (which just exchanges a[N] with itself if n is odd). You have to define a single temp variable to use in making each exchange.

Edit: You can also use reverse() from the Standard Library. Just pass it pointers to the beginning and one past the end of the array.

Edit: Ignore the previous edit. That's C++ only. - 03-29-2007quzah
- 03-29-2007robatino
> There is no reverse function in the standard C library.

Sorry, forgot which forum I was in. - 03-29-2007NoirQuote:

There is no reverse function in the standard C library.

- 03-29-2007quzah
- 03-29-2007Noir
It's not standard? I didn't know that. Thanks.

- 03-29-2007Noir
I tried to do this without knowing the type of the array, but I'm not sure if it's the best way. Can you look at my code and tell me if I'm doing anything wrong?

Code:`void reverse( void *array, int nelem, int size ) {`

char *carray = array;

int i = 0;

if ( size == 1 ) {

char temp;

for ( ; i < --nelem; i++ ) {

temp = carray[i];

carray[i] = carray[nelem];

carray[nelem] = temp;

}

} else {

#define elem(i) ( carray + ( i * size ) )

void *temp = malloc( size );

for ( ; i < --nelem; i++ ) {

memcpy( temp, elem( i ), size );

memcpy( elem( i ), elem( nelem ), size );

memcpy( elem( nelem ), temp, size );

}

free( temp );

#undef elem

}

}

- 03-29-2007robatino
You shouldn't have to treat size == 1 as a separate case (except possibly for efficiency). Also, the malloc() cries out to be checked for NULL. It should be possible to avoid using it, perhaps by using a char for temp and copying size times? I'm not familiar with memcpy() or with endianness issues so I'm not sure whether it will work.

- 03-29-2007vart
- 03-30-2007Noir
The special case is exactly for efficiency. I like the byte copying thing, I'll try that out. :)

- 03-30-2007iMalc
I would probably use alloca, rather than malloc, for something like this. Then you definitely don't need the special case.

Or you can just copy a byte at a time, even though that might be a little slower than a memcpy. - 03-30-2007dwks
alloca() isn't standard either . . . .

It can be done with a simple loop. It depends on what the OP wants.

Code:`void reverse_array(int *array, int number) {`

int x, t;

for(x = 0; x < number; x ++, number --) {

t = array[x];

array[x] = array[number];

array[number] = t;

}

}

- 03-30-2007iMalc
I was continuing with the "without knowing the type of the array" idea.

If the type is known, I'd swap items as per dwks' code, just like any other sane person.