c - QSorting a malloc'd array of structures?

标签 c pointers struct qsort

我在 C 中为我的 qsort 使用了这个比较器函数,但无论我尝试什么,我似乎都会遇到段错误...

int textCompare ( const void * a, const void * b ){
    const char **x =(const char**)a;
    const char **y =(const char**)b;
    return strcmp(*x, *y);
}

这是我的 qsort 调用:其中 message** mList = malloc(INITIAL_CAPACITY * sizeof(message));count 是一个跟踪最后一个元素的整数. message 只是一个 typedef 结构,它包含一个 int 和一个指向 char 的指针。我有 67% 的把握调用 qsort 是正确的,任何人都可以指出正确的方向吗?

qsort (*mList, count, sizeof(message), textCompare);

[编辑] 我声明 message*** 而不是 message* 的原因是因为我试图初始化一个指向结构的指针“数组”;除非我以错误的方式解决这个问题?

最佳答案

如果你确实想对指向消息结构的指针数组进行排序,那么你需要使用这个

message **mlist = (message **)malloc(INITIAL_CAPACITY * sizeof(message *));

然后您必须为数组中的指针指向的每条消息分配内存。

for(int i=0; i<INITIAL_CAPACITY; i++) {
  mlist[i] = (message *)malloc(sizeof(message));
  /*  initialize the members here  */
  mlist[i]->int = get_int();
  mlist[i]->char = get_char();  
  count++
  if(count >= NUM_TO_FILL_RIGHT_NOW)
   break;   
} 

现在您可以对指针数组而不是结构本身进行排序。

int textCompare( const void *a, const void *b ) {
  message *m1 = *(message **)a;
  message *m2 = *(message **)b;
  return strcmp(m1->char, m2->char);
}

现在对指针数组调用 qsort

qsort( mlist, count, sizeof(message *), textCompare );  

使用这种方法,指针位于连续的内存中(理论上),但结构本身会根据需要单独分配。此外,由于被复制对象的大小,排序指针通常比排序结构更快。指针在 64 位机器上是 8 个字节,在 32 位机器上是 4 个字节,您的结构实际上可能比那个小,但典型的结构会比指针大。

关于c - QSorting a malloc'd array of structures?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5228200/

相关文章:

c++ - 返回对指针的引用 - C++

c - 在C中解析和发送数据帧

c - 结构的 Malloc'ing 指针到指针成员

c - 用 C 语言求解二维数组迷宫

c - C语言必须自动生成一些权重图库吗?

c - C中的结构体到数组

C++ 指向另一点的指针

c++ - oid 将 double* 转换为 double

创建结构参数

c++ - int16_t 到 float 转换怪异