Q对 malloc 的结构数组进行排序?

0 c struct pointers 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);
}
Run Code Online (Sandbox Code Playgroud)

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

qsort (*mList, count, sizeof(message), textCompare);
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*rey 5

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

message **mlist = (message **)malloc(INITIAL_CAPACITY * sizeof(message *));
Run Code Online (Sandbox Code Playgroud)

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

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;   
} 
Run Code Online (Sandbox Code Playgroud)

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

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

现在对指针数组调用 qsort

qsort( mlist, count, sizeof(message *), textCompare );  
Run Code Online (Sandbox Code Playgroud)

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