c - How to qsort array of integer pointers?
问题描述
I have the following function that needs to return an array of pointers to a sorted list
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;
}
And the comparator function
int comp_list_asc(const void *a, const void *b)
{
int *A = *(int **)a;
int *B = *(int **)b;
return (A - B);
}
When I input an array E.G: 3 2 5
I'm getting the same output 3 2 5
, what I'm doing wrong ?
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);
}
解决方案
You're subtracting pointers, instead of integers. The below change should work for you.
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
}
As pointed out by @tstanisl, subtracting integers is prone to overflow/underflow errors. These can be addressed by changing the return statement like below.
return *A == *B ? 0 : *A < *B ? -1 : 1;
推荐阅读
- javascript - 在两个不同的点击事件之间传递数组值
- python - 在 jupyter notebook 中使用 .so python 库进行多处理
- javascript - 根据JS中的另一个数组对Array的一部分进行排序
- c++ - assert 对于我给它的每个输入都在 bash 中工作,即使它是错误的?如何解决这个问题?
- pentaho - 在根级别的 Javascript 作业条目中设置变量
- c - Linux syscall clock_settime(...) 在 Docker 容器中因 EPERM 而失败
- json - 使用 SwiftyJSON 从 NSObject 创建 JSON 文档
- cassandra - Cassandra system_auth 复制因子 2 是什么意思?
- java - Spring session 延迟反序列化
- java - Android Studio 无法将文件粘贴到资产文件夹