Vector ordering of character vectors with qsort stdlib.h

0

The next program is not ordering the chars vector vector correctly, but I do not know why. Maybe it's my helper function "cmpstr" that is not returning the right value in some cases, or my qsort call ... What's wrong?

#include <stdio.h>
#include <stdlib.h> //qsort
#include <string.h> //strcmp

int cmpstr(const void* a, const void* b){ // função auxiliar do qsort
    const char* aa = (const char*)a;
    const char* bb = (const char*)b;
    return strcmp(aa, bb);
}

char equipe[1000][5000][50]; //array de arrays de arrays de caracteres

int main()
{
    int qtd_alunos, qtd_times, qtd_membros;
    scanf("%d %d", &qtd_alunos, &qtd_times);
    qtd_membros = qtd_alunos/qtd_times;

    for(int j=0; j<qtd_membros; j++){   //recebe nomes
        for(int i=0; i<qtd_times; i++){
            scanf("%s", equipe[i][j]);
        }
    }

    for(int j=0; j<qtd_times; j++){  //ordena cada equipe [deveria ordenar]
        qsort(equipe[j], qtd_membros, sizeof(char*), cmpstr);
    }
    for(int i=0; i<qtd_times; i++){  //exibe a composição de cada equipe
        printf("Time %d\n", i+1);
        for(int j=0; j<qtd_membros;j++){
            printf("%s\n", equipe[i][j]);
        }
        printf("\n");
    }
    return 0;
}
    
asked by anonymous 16.06.2016 / 06:54

1 answer

1

Wrong

    qsort(equipe[j], qtd_membros, sizeof(char*), cmpstr);
    //                            ^^^^^^^^^^^^^

The equipe array has size sizeof (char) * 50 * 5000 * 1000 (same as sizeof equipe ). Each element of this array (each team) has sizeof (char) * 50 * 5000 (same as sizeof equipe[0] ). Each element of each team (each member) has sizeof (char) * 50 size (same as sizeof equipe[0][0] ).

Solution

    qsort(equipe[j], qtd_membros, sizeof equipe[0][0], cmpstr);
    //                            ^^^^^^^^^^^^^^^^^^^
    
16.06.2016 / 11:47