c - 指向整数的指针数组

标签 c arrays sorting pointers

我正在尝试对指向整数的指针数组(而不是整数数组本身)进行排序

但是当我尝试将指针数组初始化为整数数组中的整数地址时,我的程序崩溃了。

int** pointerSort(int* arr, int size)
{

    int i;

    // allocate memory for result array and verify success of allocation
    int** res = (int**)malloc(size*sizeof(int*));
    if (res = NULL)
    {
        printf("Memory allocation failed\n");
        exit(1);
    }

    // initialize pointers array with addresses
    for (i = 0; i < size; i++)
        res[i] = &(arr[i]);

    // sort the array using merge sort algorithm
    mergeSort(res, size-1);

    return res;
}

我的程序在 res[i] = &(arr[i]); 时崩溃

最佳答案

if (res = NULL) 这里您将 NULL 分配给 res
你想比较,而不是赋值,你应该使用==

值得一提的是,赋值表达式返回赋值,在本例中为NULL
在您的代码中,即使 malloc 分配内存失败,if 语句也可能被评估为 false

这是我们应该带警告编译的另一个很好的理由!

关于c - 指向整数的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655301/

相关文章:

ios - 如何通过定时器索引数组并绑定(bind)到 View ?

c++ - 如何按值对数组进行排序(排序)? *有一个转折*

开罗字形缓存

c - 在 C 中并行化 for 循环

c - 没有线程的竞争条件?

arrays - 如何对整数和字符串数组进行排序?

arrays - 用形状 react proptype 数组

php - 循环以按字母顺序返回所有 Woocommerce 产品标签

javascript - 按日期对 JSON 对象数组进行排序

c - 编写 Linux 键盘驱动程序