Vector sorting of character vectors with qsort <stdlib. h>

Asked

Viewed 630 times

0

The following program is not ordering the chars vector correctly, but I don’t know why. Maybe it’s my auxiliary function "cmpstr" that isn’t 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;
}
  • Possibly you have cycles (or indices) in the scanf() change.

1 answer

1


Wrong

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

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


Solution

    qsort(equipe[j], qtd_membros, sizeof equipe[0][0], cmpstr);
    //                            ^^^^^^^^^^^^^^^^^^^
  • Arrays and pointers nay are the same thing. I recommend reading section 6 of FAQ of comp.lang. c.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.