我正在尝试对整数指针数组进行排序(而不是对整数数组本身进行排序)
但是,当我尝试初始化指向整数数组中整数地址的指针数组时,我的程序崩溃了。
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
。
在您的代码if
中false
,即使malloc
分配内存失败,语句也可以评估为。
这是我们应该编译警告的另一个很好的理由!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句