码迷,mamicode.com
首页 > 编程语言 > 详细

How does “void *” differ in C and C++?

时间:2015-09-22 18:38:33      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

http://www.geeksforgeeks.org/g-fact-12-2/

C allows a void* pointer to be assigned to any pointer type without a cast, whereas C++ does not; this idiomappears often in C code using malloc memory allocation. For example, the following is valid in C but not C++:

 1 void* ptr; 2 int *i = ptr; /* Implicit conversion from void* to int* */ 

or similarly:

 1 int *j = malloc(sizeof(int) * 5); /* Implicit conversion from void* to int* */ 

In order to make the code compile in both C and C++, one must use an explicit cast:

1 void* ptr;
2 int *i = (int *) ptr;
3 int *j = (int *) malloc(sizeof(int) * 5);

Source:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B

How does “void *” differ in C and C++?

标签:

原文地址:http://www.cnblogs.com/lyleslie/p/4829374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!