我有一個類似於下面的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