问题描述
我得到了这个线程我的回答评论:
I got a comment to my answer on this thread:
总之我有code是这样的:
In short I had code like this:
int * somefunc (void)
{
int * temp = (int*) malloc (sizeof (int));
temp[0] = 0;
return temp;
}
我得到了这个评论:
I got this comment:
我只能说,请不要投的
返回的malloc价值?不是这样
需要和可以隐藏的错误。
我同意,中投不中C.要求它在C ++强制性的,所以我通常添加他们万一我有端口C ++中的code一天。
I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.
不过,我不知道怎么蒙上这样可以隐藏错误。任何想法?
However, I wonder how casts like this can hide errors. Any ideas?
好像有两边非常好,有效的参数。感谢张贴,乡亲们。
Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.
推荐答案
看来我装修后一个答案,因为我离开的注释:P
It seems fitting I post an answer, since I left the comment :P
基本上,如果你忘了包括文件stdlib.h
编译器将假定的malloc
返回 INT
。没有铸造,你会得到一个警告。随着铸造你不会。
Basically, if you forget to include stdlib.h
the compiler will assume malloc
returns an int
. Without casting, you will get a warning. With casting you won't.
因此,通过铸造你什么也得不到,并运行SUP pressing合法警告的风险。
So by casting you get nothing, and run the risk of suppressing legitimate warnings.
很多写这个,快速谷歌搜索将更加详细的解释。
Much is written about this, a quick google search will turn up more detailed explanations.
据认为,
TYPE * p;
p = (TYPE *)malloc(n*sizeof(TYPE));
使得它很明显当你不小心,因为比方说,你以为 P
是键入
不是不分配足够的内存键入
,因此,我们应该投malloc的,因为这种方法的优点是覆盖意外燮pressing编译器警告较小的成本。
makes it obvious when you accidentally don't allocate enough memory because say, you thought p
was TYPe
not TYPE
, and thus we should cast malloc because the advantage of this method overrides the smaller cost of accidentally suppressing compiler warnings.
我想指出的两件事情:
- 您应该写
P =的malloc(sizeof的(* P)* N);
来始终确保你的malloc空间权金额 - 用上面的方法,你需要在3个地方的变化,如果你改变
P
的类型:一次报关,一次是在的malloc
,一旦中投。
- you should write
p = malloc(sizeof(*p)*n);
to always ensure you malloc the right amount of space - with the above approach, you need to make changes in 3 places if you ever change the type of
p
: once in the declaration, once in themalloc
, and once in the cast.
总之,我还是个人认为没有必要为铸造的malloc
的返回值,它肯定不是最好的做法。
In short, I still personally believe there is no need for casting the return value of malloc
and it is certainly not best practice.
这篇关于不用指针类型转换用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!