简体   繁体   English

使用 qsort function 对字符串数组进行排序

[英]sorting an array of strings with qsort function

I'm sorting an array of strings by using the qsort function.我正在使用qsort function 对字符串数组进行排序。

char treeName[100][31];

By trial and error, I figured out that it should be done like this:通过反复试验,我发现应该这样做:

qsort(&treeName[0], count, sizeof(*treeName), Comparar_nome);

However, I am not entirely sure why sizeof(*treeName) .但是,我不完全确定为什么sizeof(*treeName) Shouldn't it be sizeof(char) * 31 , or something like that?不应该是sizeof(char) * 31或类似的东西吗?

   qsort(&treeName[0], count, sizeof(*treeName),Comparar_nome);

Can be broken down as follows:可以细分如下:

    qsort

The function call. function 电话。

    &treeName[0]

Address of the start of the array.数组的起始地址。 Can be simplified to treeName .可以简化为treeName

    count

The number of entries in treeName actually used. treeName中实际使用的条目数。

    sizeof(*treeName)

The size of an array element.数组元素的大小。 I would have written this is sizeof(treename[0]) but there's no difference.我会写这是sizeof(treename[0])但没有区别。 sizeof(char)*31 really should have worked. sizeof(char)*31确实应该有效。 Are you sure you didn't have something else broken when you tried it?您确定尝试时没有其他东西坏了吗? We were unable to find a real compiler for which this would not work.我们无法找到一个真正的编译器,这对它不起作用。 sizeof(*treename) is better anyway for readability and should that 31 ever change.无论如何, sizeof(*treename)的可读性更好,而且31是否应该改变。

    Comparar_nome

Address of the function that compares tree nodes.比较树节点的地址function。 You wrote it correctly;你写对了; &Comparar_nome is archaic style. &Comparar_nome是古老的风格。

If treeName is indeed defined as char treeName[100][31];如果treeName确实被定义为char treeName[100][31]; in the scope of the function calling qsort , your code is correct:在 function 调用qsort的 scope 中,您的代码是正确的:

qsort(&treeName[0], count, sizeof(*treeName), Comparar_nome);

You could write this equivalently:你可以等效地写这个:

qsort(treeName, count, sizeof treeName[0], Comparar_nome);

Note however that Comparar_nome must have the correct prototype:但是请注意Comparar_nome必须具有正确的原型:

int Comparar_nome(const void *a, const void *b);

A simple implementation being:一个简单的实现是:

#include <stdio.h>

int Comparar_nome(const void *a, const void *b) {
    return strcmp(a, b);
}

Passing strcmp instead of Comparar_nome would be a type mismatch invoking undefined behavior that would go unnoticed in many architectures but is nevertheless incorrect.传递strcmp而不是Comparar_nome将是一种类型不匹配,会调用未定义的行为,这 go 在许多体系结构中都不会被注意到,但仍然是不正确的。

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

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