小编The*_*ark的帖子

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

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

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 …

c qsort

0
推荐指数
1
解决办法
164
查看次数

标签 统计

c ×1

qsort ×1