Sort strings on a struct array in C

Asked

Viewed 50 times

0

I’m trying to sort alphabetically strings in a string array in a struct, but for some reason the names get bugged

#define TV 10
#define TC 100

typedef struct ficha {
    char nome[TC];
    int dependentes;
    float salario;
    int atendimentos;
    char email[TC];
} FICHA;

...

void ordenarDadosString(FICHA usuario[TV], int qntdUsuarios)
{
    int i, trocou, ls = qntdUsuarios - 1;
    char aux[TC];
    aux[TC - 1] = '\0';
    do {
        trocou = 0;
        for(i = 0; i < ls; i++) {
            if(strcmp(usuario[i].nome, usuario[i + 1].nome) > 0) {
                strcpy(usuario[i].nome, aux);
                strcpy(usuario[i + 1].nome, usuario[i].nome);
                strcpy(aux, usuario[i].nome);
                trocou = 1;
            }
        }
        ls--;
    } while(trocou);
}

Here is a print of what appears when trying to sort http://prntscr.com/li0wuw Here the full code, if it helps https://pastebin.com/pBjSEUGZ

  • Ordain structs based on a field of struct that’s it ?

  • yes, exactly this, in case I managed to do this with variable int, but with error strings at the time of making the exchange, do not know pq

  • This question has basically what you want although the comparison is done in an entire field instead of in a string. In practice changes very little even, just have to use the strcmp instead of comparing directly

  • I was, I was trying to understand what it was like in the example they sent me, thank you guys

No answers

Browser other questions tagged

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