Zwracanie tablicy struktur

0

Witam,
Mam pewiem problem otóż mam funkcję:

struct student ** najlepsi(int ** ile)
{
    struct student  ** najlepsi;
    struct student s[50];
    int i=0;
    int x=0;
    int b=1;
        FILE *plik;
    plik=fopen("dane.bin","r");
    while(fread(&s[i],sizeof(struct student),1,plik)!=0)
    {
        i++;
    }
     fclose(plik);
    for(x=0;i<x;x++)
    {
        if(s[x].srednia>4.75)
        {
            najlepsi=(struct student*)realloc(najlepsi,b*sizeof(struct student));
            najlepsi[b-1]=s[x];
            b++;

        }
        printf("%s",*(najlepsi)->nazwisko);
    }
    *ile=b;
    return najlepsi;

};

Jak powinno wyglądać wywołanie takiej funkcji w mainie ?

0

Patrząc po nagłówku funkcji to coś takiego:

struct student bestOfTheBest = najlepsi(10);

A po ciele funkcji to coś takiego:

struct student *bestOfTheBest = najlepsi(10);
1

Ten kod jest strasznie koślawy i ma troszkę UB.
To powinno być raczej coś w tym stylu:

int filterRequriedAverage(struct student* s, void *context)
{
     double *average = (double *)context;
     return (s.srednia>*average)?1:0;
}

int loadWithFilter(FILE *file, 
                   struct student **result,
                   int (*predicate)(struct student* s, void *context),
                   void *context = NULL)
{
    struct student s;
    int count = 0;
    struct student *filteredData = NULL;

    while(fread(&s, sizeof(s), 1, file) == 1)
    {
        if(predicate(&s, context) != 0)
        {
              count++;
              filteredData = (struct student*)realloc(filteredData, count*sizeof(s));
              filteredData[count - 1] = s;
        }
    }
    *result = filteredData;
    return count;
};

void test()
{
        struct student *data = NULL;

        FILE *f=fopen("dane.bin","r");
        double neededAverage = 4.75;
        int count = loadWithFilter(f, &data, &filterRequriedAverage, &neededAverage);
        close(f);

        doSomthingWith(data, count);

        free(data);
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1