【发布时间】:2020-05-11 20:28:22
【问题描述】:
我的程序有一堆指针,比如
int* one;
int** two;
int*** three;
我想在对它们使用 realloc 时检查内存分配错误。我知道如果分配失败 realloc 返回NULL 所以我做了以下函数:
void checkMemoryAllocationError(const void *a){
if (a == NULL){
fprintf(stderr, "Realloc failed");
exit(5); //5 is arbitrary
}
}
我可以通过以下方式调用这个函数吗?
checkMemoryAllocationError(one);
...
checkMemoryAllocationError(two);
...
checkMemoryAllocationError(three);
或者说二和三是指向指针的指针这一事实是否有所不同?我宁愿在我的代码体中重复没有 if 语句,那么这个解决方案是否有效,或者有没有更好的方法来做到这一点,我错过了?
【问题讨论】:
-
请注意,有许多指向指向指针的指针的实例是程序可以改进的标志。你通常不想成为Three Star Programmer。