QSorting一个malloc的结构数组? [英] QSorting a malloc'd array of structures?

查看:56
本文介绍了QSorting一个malloc的结构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this comparator function for my qsort in C, but I seem to be getting a segmentation fault no matter what I try...

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,有人能指出我正确的方向吗?

Here is my qsort call: where message** mList = malloc(INITIAL_CAPACITY * sizeof(message)); and count is an integer keeping track of the last element. message is just a typedef struct that contains an int and a pointer to a char. I'm 67% sure that I am calling qsort correctly, can anyone point me in the right direction?

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

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

The reason I declare message*** instead of message* is because I'm trying to initialize an "array" of pointers to structures; unless I'm going about this the wrong way?

推荐答案

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

If you do actually want to sort an array of pointers to message structs, then you would need to use this

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

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

Then you have to allocate memory for each message being pointed to by the pointers in the array.

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;   
} 

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

now you can sort the array of pointers instead of the structures themselves.

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

现在对指针数组调用 qsort

Now call qsort on the array of pointers

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

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

with this method, the pointers are in contiguous memory(theoretically), but the structures themselves are malloced individually as needed. Also, sorting pointers is usually faster than sorting structures because of the size of the object being copied. Pointers are 8 bytes on a 64 bit machine, and 4 bytes on a 32 bit machine, and your structure may actually be smaller than that, but a typical structure will be larger than a pointer.

这篇关于QSorting一个malloc的结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆