lundi 25 juillet 2016

Qsort of dynamically allocated array of dynamically allocated strings by string length

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 20

int compare(const void* a, const void* b) {
    return strlen((char*)a) - strlen((char*)b);
}

int main() {
    int i, n;
    scanf("%d", &n);
    char** strings = malloc(n*sizeof(char*));
    for(i=0; i<n;i++) {
        strings[i]=(char*)malloc(sizeof(char*));
        scanf("%s", strings[i]);
    }
    qsort(strings, n, sizeof(char*), compare);
    for(i=0; i<n;i++)
        printf("%sn", strings[i]);
    for(i=0; i<n;i++)
        free(strings[i]);
    free(strings);
    return 0;
}

So I tried doing it like this but it returns a unsorted array and I got no idea what should be changed, anyone knows how to do this?


[update from comment:]

I forgot to mention, it should be sorted by length of strings.

Aucun commentaire:

Enregistrer un commentaire