How do you reverse an array?
Printable View
How do you reverse an array?
search forum for reverse string assignments
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.
> There is no reverse function in the standard C library.
Sorry, forgot which forum I was in.
What about strrev()?Quote:
There is no reverse function in the standard C library.
It's not standard? I didn't know that. Thanks.
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
}
}
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.
The special case is exactly for efficiency. I like the byte copying thing, I'll try that out. :)
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.
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;
}
}
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.