Malloc和数据类型 [英] Malloc and data types

查看:81
本文介绍了Malloc和数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


为什么这样不起作用:

Hy
Why this doesn''t work:

int main (void) {

	int *x = NULL;

	x = malloc (sizeof(int));

	free(x);

	x = NULL;

	getchar();

	return 0;
}



它说它不能从``void *''转换为``int *''



It says that it cannot convert from ''void *'' to ''int *''

推荐答案

malloc()函数返回指向已分配内存的指针,如下所示: void*,必须(由您)强制转换为适当的类型.因此,您需要更改代码,以便让编译器知道您正在执行的操作:
The malloc() function returns a pointer to the allocated memory as a void* which must be cast (by you) to the appropriate type. You need to change your code thus, in order to let the compiler know that you understand what you are doing:
x = (int*)malloc (sizeof(int));



[由AH编辑]
malloc()返回void*的原因是因为它是通用调用,以字节为单位分配内存.为什么要通用?因此,它可用于为任何类型的数据(字符,整数,双精度型,结构,真正的任何东西)分配内存.
[/edit]



[edit by AH]
The reason malloc() returns a void* is because its a generic call to allocate memory in bytes. Why generic? So it can be used to allocate memory for any type of data (characters, integers, double, structures, anything really).
[/edit]


这篇关于Malloc和数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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