John Nickols
John Nickols

Reputation: 23

C: Sorting a pointer structure array by pointer key

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.)

Upvotes: 2

Views: 1052

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183888

names is used as an array of nameType, but

nameType *tmp;
tmp = names[ i ];

you assign names[i] to a pointer to nameType. Make it nameType tmp;.

And of course make sure you don't overstep the allocated space for names, as @another.anon.coward said, j should probably start from n-1.

Upvotes: 2

Related Questions