简体   繁体   English

将参数从传递给qsort()函数<stdlib.h>

[英]Passing parameters to qsort() function from <stdlib.h>

This is the data type that I declared: 这是我声明的数据类型:

struct Element{
    char name[21], symbol[4];
    double atomicMass;
    int valence;
};
typedef struct Element myElements;
myElements data[20];

If I just want to pass the name members of 如果我只想传递名称的成员

data[20] 

to qsort(), how to do that? 到qsort(),该怎么做?

Not sure if this would be the correct way to pass to the function: 不知道这是否是传递给函数的正确方法:

qsort(data->name, 20, sizeof(myElements), compare);

You don't pass just member. 您不只是通过成员。 Right way is to write a helper compare function which compares 2 elements by their name and use it. 正确的方法是编写一个助手比较函数,该函数按名称比较2个元素并使用它们。

static int
cmpElement(const void *p1, const void *p2)
{
    return strcmp(((const Element *) p1)->name, ((const Element *) p2)->name);
}

qsort(data, 20, sizeof data[0], cmpElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM