如何对整数指针数组进行排序?

The*_*ark 0 c qsort

我有以下函数需要返回指向排序列表的指针数组

int **list_elements_sorted(int *array, int n)
{
  if (n <= 0)
  {
    return NULL;
  }

  int **sorted_list = malloc(n * sizeof(int *));
  assert((sorted_list != NULL) && "Error! Memory allocation failed!");

  for (int i = 0; i < n; i++)
  {
    sorted_list[i] = &array[i];
  }

  qsort(sorted_list, n, sizeof(int *), comp_list_asc);

  return sorted_list;
}
Run Code Online (Sandbox Code Playgroud)

和比较器功能

int comp_list_asc(const void *a, const void *b)
{
  int *A = *(int **)a;
  int *B = *(int **)b;

  return (A - B);
}
Run Code Online (Sandbox Code Playgroud)

当我输入数组 EG 时:3 2 5我得到相同的输出3 2 5,我做错了什么?

void test_sorted_list_valid_3(void **state)
{
  int **output;

  int n = 3;
  int int_list[] = {3, 2, 5};
  int *int_list_sorted[] = {&int_list[1],
                            &int_list[0],
                            &int_list[2]};

  output = list_elements_sorted(int_list, n);

  assert_memory_equal(int_list_sorted, output, n);
  free(output);
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*tal 5

您减去的是指针,而不是整数。以下更改应该适合您。

int comp_list_asc(const void *a, const void *b)
{
  int *A = *(int **)a;
  int *B = *(int **)b;

  return (*A - *B); // here's the change
}
Run Code Online (Sandbox Code Playgroud)

正如@tstanisl 所指出的,整数相减很容易出现上溢/下溢错误。这些可以通过更改返回语句来解决,如下所示。

return *A == *B ? 0 : *A < *B ? -1 : 1;
Run Code Online (Sandbox Code Playgroud)