0

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

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

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]);

4

2 回答 2

12

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

值得一提的是,赋值的表达式返回赋值的值,在这种情况下,它是NULL.
在您的代码中,即使未能分配内存,if语句也可以评估为。falsemalloc

这是我们应该使用警告进行编译的另一个好理由!

于 2013-07-15T13:24:20.040 回答
4

正如其他答案所示,问题是您的作业用作条件:

if (res = NULL)

但这里有一个避免这种特定故障模式的提示:将文字放在左侧:

if (NULL = res)

NULL(和其他文字)不是合法的左值,也就是说——它们没有被合法分配,所以如果你或维护者不小心删除了表达式中关键的二等号字符,你的编译器将拒绝继续。

于 2013-07-15T13:29:12.360 回答