关于如何对结构指针数组进行排序,有很多关于stackoverflow的问题。我看了他们所有,无济于事。我想对一组结构数组进行排序。我首先为指针数组分配存储,然后为结构本身分配存储。一切看起来都不错,但我无法对它们进行排序。我确定问题在于比较功能。我从stackoverflow中复制了一些,它们列在下面。但它们都不起作用......
typedef struct s_stream{
int amc;
char *name;
} dataStream;
void abc(void)
{
int count = 100;
dataStream *_UniqueStreamBuild = calloc(count, sizeof(dataStream ));
dataStream **UniqueStreamBuild = calloc(count, sizeof(dataStream *));
for ( int i = 0; i < count; ++i) UniqueStreamBuild[i] = _UniqueStreamBuild + i;
//**Edit: ******** **
// here I call a cascade of functions that assign values to amc; those
// functions are correct: they produce an unsorted array of amc values;
// the output I am getting is an array of structures seemingly in random order.
qsort(UniqueStreamBuild, count, sizeof(dataStream *), compare);
}
int compare (const void * a, const void * b)
{
const dataStream *x = a;
const dataStream *y = b;
if (x->amc > x->amc)
return(1);
if (x->amc < x->amc)
return(-1);
return(0);
}
int compare( const void *a, const void *b )
{
dataStream *m1 = *(dataStream **)a;
dataStream *m2 = *(dataStream **)b;
if (m1->amc > m2->amc)
return(1);
if (m1->amc < m2->amc)
return(-1);
return(0);
}
答案 0 :(得分:1)
你的第二个可能的compare()
函数应该可以工作,除非我之间没有注意到它与下面这个版本之间没有注意到。在对指针数组进行排序时,比较函数会传递两个指向dataStream *
的指针,因此比较器应该非常类似于此:
int compare (const void *a, const void *b)
{
const dataStream *x = *(const dataStream **)a;
const dataStream *y = *(const dataStream **)b;
if (x->amc > y->amc)
return(1);
else if (x->amc < y->amc)
return(-1);
else
return(0);
}
此外,正如最初编写的那样,您的某个函数始终返回0,因为x->amc == x->amc
(您取消引用x
两次,而不是x
和y
)。
您的测试代码没有完全初始化数据结构 - 它使用calloc()
因此结构中的字符串和指针都被清零,因此排序不会做太多。
这段代码对我有用......你呢?
#include <stdio.h>
#include <stdlib.h>
typedef struct s_stream
{
int amc;
char *name;
} dataStream;
static int compare(const void *a, const void *b)
{
const dataStream *x = *(const dataStream **)a;
const dataStream *y = *(const dataStream **)b;
if (x->amc > y->amc)
return(1);
else if (x->amc < y->amc)
return(-1);
else
return(0);
}
static void dump(FILE *fp, const char *tag, dataStream * const * const data, int num)
{
const char *pad = "";
fprintf(fp, "Stream Dump (%s): (%d items)\n", tag, num);
for (int i = 0; i < num; i++)
{
fprintf(fp, "%s%d", pad, data[i]->amc);
if (i % 10 == 9)
{
putc('\n', fp);
pad = "";
}
else
pad = ", ";
}
putc('\n', fp);
}
static void abc(void)
{
int count = 100;
dataStream *_UniqueStreamBuild = calloc(count, sizeof(dataStream ));
dataStream **UniqueStreamBuild = calloc(count, sizeof(dataStream *));
for ( int i = 0; i < count; ++i)
{
UniqueStreamBuild[i] = _UniqueStreamBuild + i;
UniqueStreamBuild[i]->amc = (7 * i + 3) % count + 1;
}
dump(stdout, "Before", UniqueStreamBuild, count);
qsort(UniqueStreamBuild, count, sizeof(dataStream *), compare);
dump(stdout, "After", UniqueStreamBuild, count);
free(_UniqueStreamBuild);
free(UniqueStreamBuild);
}
int main(void)
{
abc();
return 0;
}