我有一个类似于下面的C程序。我正在尝试在malloc
之上用int myAlloc()
的签名编写包装。这个包装器应该在成功分配内存时返回1,如果内存分配失败,则返回0。不兼容的指针类型警告
#include <stdio.h>
#include <stdlib.h>
int myAlloc(void **ptr, int size)
{
*ptr = malloc(size);
if (!ptr)
return 0;
else
return 1;
}
void main()
{
int *p = NULL;
myAlloc(&p, sizeof(int));
printf("%d\n", *p);
}
当我编译这个时,我得到一个警告说“不兼容的指针类型”。我怎样才能使用任何可能的指针类型调用此函数而不接收警告?
是否可以从实际的函数调用中移除铸造操作?
更新
我找到了答案。下面是更正后的代码:
#include <stdio.h>
#include <stdlib.h>
int myAlloc(void *ptr,int size)
{
*(void **)ptr = malloc(size);
if (!ptr)
return 0;
else
return 1;
}
int main()
{
int *p = NULL;
myAlloc(&p, sizeof(int));
*p = 5;
printf("%d\n", *p);
return 1;
}
这似乎不是标准C,或C++,作为主要不返回无效。 – 2012-03-23 13:30:49
@ RichardJ.RossIII你错了。阅读[this](http://stackoverflow.com/questions/5296163/why-is-the-type-of-the-main-function-in-c-and-c-left-to-the-user-to -define/5296593#5296593)。 – Lundin 2012-03-23 13:31:53
@Lundin我已经读过了,我的观点依然存在。我不相信这是在独立的环境或托管环境中。 – 2012-03-23 13:33:24