malloc一定要强制类型转换吗

来源:百度知道 编辑:UC知道 时间:2024/09/21 22:51:34
struct student
{
int num;
float score;
};

struct student *p;

p = (struct studedt *) malloc(sizeof(struct student));

这个 (struct studedt *)强制类型转换是必须的吗?
如果是,在宏定义里怎么样写比较好呢?

不一定必要 就看你怎么用它了(- -!)
在宏定义中,为了方便,你可以这么写
#define studentptr (struct student *)
#define studentlen sizeof(struct student)
#define getstudentmem studentptr malloc(studentlen)

这样以后就非常好办了
比如你要申请内存
你只要
studentptr p = getstudentmem;//这样就可以申请一片struct student的内存

必须的,因为malloc的返回类型是void指针类型的,必须转换成目标指针类型,才能对指针进行操作如自增、自减、引用等。

宏定义,好像没办法,也没见到过。

不一定,用宏定义为
#define LEN (struct student)