I have this structure:
typedef struct {
char *str;
...
} nameType;
I create a new pointer instance, initialize the str pointer inside it (all of these have been done correctly, I can do printfs to check it).
nameType *names;
names = malloc( 10 * sizeof( nameType ) );
for ( i = 0; i < 10; i++ ) {
...
names[ i ].str = malloc( ... );
...
}
And then I want to sort it using bubblesort, but I’m having trouble doing it. Noted that I managed to do it using qsort, but after some days of debugging, testing, googling etc, I still can’t find it. Sorting code:
for ( i = 0; i < n - 1; i++ ) {
for ( j = n - 1; j > i; j-- ) {
if ( strcmp( names[ i ].str, names[ j ].str ) > 0 ) {
nameType *tmp;
tmp = names[ i ];
names[ i ] = names[ j ];
names[ j ] = tmp;
}
}
}
(The above code is just an example of what I’m doing with sorting — I’ve tried so many variations that my mind is going to blow.)
namesis used as an array ofnameType, butyou assign
names[i]to a pointer tonameType. Make itnameType tmp;.And of course make sure you don’t overstep the allocated space for
names, as @another.anon.coward said,jshould probably start fromn-1.