megat
megat

Reputation: 3

qsort funcation work with structre which carry char poiter member

I can't understand following qsort call qsort(cricketer,7,sizeof(struct player),comp);

How is the size of "struct player" calculated because in struct player member char *name; is not static.

struct player
{
    char* name;
    int age, ntm, ar;
}

cricketer[20]={
                "sam",35,10,300,
                "ram",55,15,200,
                "aman",45,19,300,
                "raman",65,22,400,
                "mani",75,25,350,
                "mono",76,10,215,
                "verma",88,16,103
    };
int comp(const void* a,const void* b)
{
    const struct player * x = (const struct player*)a;
    const struct player * y = (const struct player*)b;
    if(x->age > y->age)return 1;
    else return 0;
}

void read()
{
for (int i = 0; i < 7; i++)
    printf("\n\t\tName : %s\t\tAge : %d\t\tNum of Matches : %d\t\tTotal score : %d\n\n ", cricketer[i].name, cricketer[i].age, cricketer[i].ntm, cricketer[i].ar);
}

int main()
{
    read();
    printf("\n\t\tAfter Qsort : %d\n", sizeof(struct player));
    qsort(cricketer,7,sizeof(struct player),comp);
    read();
    return 0;
}

Upvotes: 0

Views: 40

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

For starters this comparison function

int comp(const void *a,const void *b)
{
    const struct player *x=(const struct player*)a; const struct player *y=(const struct player*)b;
    if(x->age > y->age)return 1;



    else return 0;
}

is invalid. It shall return three values: a positive, a negative or zero depending on compared values. But the function returns only two values: either 1 or 0.

The structure contains four members

struct player{
    char *name;
    int age,ntm,ar;
};

So its size is calculated like sizeof( char * ) + sizeof( int ) + sizeof( int ) + sizeof( int ) + a posible padding for alignment.

That is the size of the structure is known at the compile time independent on what string is pointed to by the data member name. The string pointed to by the data member name is not a member of the structure. For example the pointer can be initialized by NULL.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409196

The structure contains the pointer name, not the memory that the pointer might actually point to. Therefore the size is well-known as it only include the size of the pointer itself.

Upvotes: 0

Related Questions