指向整数的指针数组

Qua*_*ker 0 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*oun 12

if (res = NULL)在这里你要分配NULLres.
你想比较,而不是分配,你应该使用==.

值得一提的是,赋值的表达式返回赋值,在本例中为它NULL.
在您的代码iffalse,即使malloc无法分配内存,也可以对语句进行求值.

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

  • 这就是为什么你应该编译警告. (4认同)
  • +1,良好的警告比yoda条件好很多.在C中使用`if(!res)`是完全惯用的. (3认同)