在C语言中,定义如下的结构类型,这个是正确的定义:
struct student *st = malloc(sizeof(struct student));
但是在C++语言中,需要按照如下的定义强制转换:
struct student *st = (struct student *) malloc(sizeof(struct student));
强制转换为了匹配不同的数据类型以实现相应的代码功能。
(struct student *) 这个就是强制转换符,因为等号的左边是自己定义的一个struct 类的量student,右边开辟了一个堆空间,但是注意malloc返回值是一个void类型的量,左右两边的数据类型不同,所以需要强制转换成同一个类型,从而实现st大小的随意分配。
本文探讨了C语言与C++语言中内存分配的不同之处,特别是在使用malloc进行堆内存分配时的区别。C语言直接使用structstudent*st=malloc(sizeof(structstudent));而在C++中,则需要使用强制类型转换structstudent*st=(structstudent*)malloc(sizeof(structstudent))。
2746

被折叠的 条评论
为什么被折叠?



