This declaration of an array
const char *str_arr[]
means that you have an array of pointers to (first characters of ) strings. That is elements of the array are pointers. And to sort the array you need to swap the elements that is pointers that point to strings.
Here is a demonstrative program that shows how such an array can be sorted according to the lexicographical comparisons of strings pointed to by elements of the array.
#include <stdio.h>
#include <string.h>
int cmp( const void *a, const void *b )
{
const char *s1 = a;
const char *s2 = b;
return strcmp( s1, s2 );
}
void bubble_sort( const char * s[], size_t n, int cmp( const void *, const void * ) )
{
for ( size_t last = n; !( n < 2 ); n = last )
{
for ( size_t i = last = 1; i < n; ++i )
{
if ( cmp( s[i], s[i - 1] ) < 0 )
{
const char *tmp = s[i];
s[i] = s[i - 1];
s[i - 1] = tmp;
last = i;
}
}
}
}
int main(void)
{
const char * s[] =
{
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
};
const size_t N = sizeof( s ) / sizeof( *s );
for ( size_t i = 0; i < N; i++ )
{
printf( "\"%s\" ", s[i] );
}
putchar( '\n' );
bubble_sort( s, N, cmp );
for ( size_t i = 0; i < N; i++ )
{
printf( "\"%s\" ", s[i] );
}
putchar( '\n' );
return 0;
}
The program output is
"zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"
"eight" "five" "four" "nine" "one" "seven" "six" "three" "two" "zero"
Using the comparison function you can specify any criteria of sorting. For example to sort the array by string lengths you can write
#include <stdio.h>
#include <string.h>
int cmp( const void *a, const void *b )
{
size_t n1 = strlen( a );
size_t n2 = strlen( b );
return ( n2 < n1 ) - ( n1 < n2 );
}
void bubble_sort( const char * s[], size_t n, int cmp( const void *, const void * ) )
{
for ( size_t last = n; !( n < 2 ); n = last )
{
for ( size_t i = last = 1; i < n; ++i )
{
if ( cmp( s[i], s[i - 1] ) < 0 )
{
const char *tmp = s[i];
s[i] = s[i - 1];
s[i - 1] = tmp;
last = i;
}
}
}
}
int main(void)
{
const char * s[] =
{
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
};
const size_t N = sizeof( s ) / sizeof( *s );
for ( size_t i = 0; i < N; i++ )
{
printf( "\"%s\" ", s[i] );
}
putchar( '\n' );
bubble_sort( s, N, cmp );
for ( size_t i = 0; i < N; i++ )
{
printf( "\"%s\" ", s[i] );
}
putchar( '\n' );
return 0;
}
At this time the program output is
"zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"
"one" "two" "six" "zero" "four" "five" "nine" "three" "seven" "eight"
If you want you can simplify the comparison function declaration the following way
int cmp( const char *, const char * )
const chartype into a simple non-const character array and then try sorting it.qsortowns to the standard library ...