它是一个更好的做法,强制转换malloc返回指针? [英] Is it a better practice to typecast the pointer returned by malloc?

查看:104
本文介绍了它是一个更好的做法,强制转换malloc返回指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于C code以下,比较INT指针a和b的defintions;

For the C code below, compare the defintions of the int pointers a and b;

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int *a=malloc(sizeof(int));
  int *b=(int *)malloc(sizeof(int));
  return(0);
}

是不是以任何方式强制转换void类型的指针,由malloc函数返回的更好吗?
或同时在左侧分配为int指针它自动类型强制转换?
在何种情况下,如果有的话,可以将其证明是必要的,而不是仅仅强制性?

Is it better in any way to typecast the pointer of type void, returned by the malloc function? Or is it auto-typecasted while assigning to the int pointer on the left hand side? Under which circumstances, if any, can it prove to be necessary rather than just obligatory?

请说明是否隐含的类型转换,其中右边的类型转换为类型的左手边,适用于这里。

Please clarify whether implicit type casting, where type of right hand side is converted to type of the left hand side, applies here.

推荐答案

不需要演员的C语言,但对于C ++的兼容性,你可能要投。这是其中C是不是C ++的子集点之一

The cast is not needed for the C language, but for C++ compatibility you may want to cast. This is one of the spots where C is not a subset of C++.

下面将编译C,但不是C ++:

The following will compile in C but not C++:

int *a=malloc(sizeof(int));

下面将C和C ++编译:

The following will compile in both C and C++:

int *b=(int *)malloc(sizeof(int));

这篇关于它是一个更好的做法,强制转换malloc返回指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆