我正在尝试对指向整数的指针数组(而不是整数数组本身)进行排序
但是当我尝试将指针数组初始化为整数数组中的整数地址时,我的程序崩溃了。
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/