Domanda

Sto cercando di ordinare un array di struct run chiamato results da un char, ma quando stampo l'array, non viene ordinato nulla.Dai un'occhiata a questo:

struct run {
  char name[20], weekday[4], month[10];
  (And some more...)
};
typedef struct run run;

int name_compare(const void *a, const void *b) 
{
    run *run1 = *(run **)a;
    run *run2 = *(run **)b;
    return strcmp(run1->name, run2->name);
}

int count_number_of_different_persons(run results[])
{
  int i = 0;


  qsort(results, sizeof(results) / sizeof(run), sizeof(run), name_compare);

  for(i = 0; i <= 999; i++)
  {
    printf("%s\n", results[i].name);
  }
  // not done with this function yet, just return 0
  return 0;
}

L'output di quanto sopra è solo un elenco di nomi nell'ordine in cui erano stati originariamente posizionati

È stato utile?

Soluzione

int count_number_of_different_persons(run results[])

Questo non ti consente di usare sizeof sull'array, perché l'array è decaduto in puntatore.

Questo

run *run1 = *(run **)a;

sembra anche strano, non dovrebbe essere

run *run1 = (run*)a;

?

Altri suggerimenti

Un problema è in name_compare.Prova questo invece:

int name_compare(const void *a, const void *b) 
{
    run *run1 = (run *)a;
    run *run2 = (run *)b;
    return strcmp(run1->name, run2->name);
}

Controlla il seguente codice:

Come menzionato da @michel, sizeof (array) fornisce la dimensione del puntatore, non la dimensione dell'array stesso, poiché durante il passaggio di array viene trattato come un puntatore.Quindi o invia il numero di elementi alla funzione count_number_of_different_persons o definisci una MACRO di numero di elementi.Spero che sia di aiuto.:).

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

#define NOE 3

struct run
{
    char name[20];
};

typedef struct run run;

int name_compare (const void *a, const void *b )
{
    return strcmp (((run *)a)->name, ((run *)b)->name);
}

int count_number_of_different_persons(run results[], int noOfElements)
{
    int i=0;
    qsort(results, noOfElements, sizeof (run), name_compare);
    for (i=0; i<noOfElements; i++)
        printf ("%s\n",results[i].name);
}

int main ( int argc, char * argv[])
{
    run a, b, c;
    run  arg[NOE];

    strcpy (a.name, "love");
    strcpy (b.name, "you");
    strcpy (c.name, "i");
    arg[0] = a;
    arg[1] = b;
    arg[2] = c;

    count_number_of_different_persons(arg, sizeof(arg)/sizeof(run));
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top