#include
#include
struct data
{
int day,month,year;
} ;
struct stu
{
char name[20];
long num;
struct data birthday;
} ;
int main()
{
struct stu *student;
student=malloc(sizeof(struct stu));
printf("Input name,number,year,month,day:/n");
scanf("%s",student->name);
scanf("%ld",&student->num);
scanf("%d%d%d",&student->birthday.year,&student->birthday.month,
&student->birthday.day);
printf("/nOutputname,number,year,month,day/n");
printf("%20s%10ld%10d//%d//%d/n",student->name,student->num,
student->birthday.year,student->birthday.month,
student->birthday.day);
return 0;
}
程序怎么出错了,求大神解答!!
错误报告是这样的。
E:\c++稿子\sdas.cpp(16) : error C2440: '=' : cannot convert from 'void ' to 'struct stu *' Conversion from 'void' to pointer to non-'void' requires an explicit cast 执行 cl.exe 时出错.
类型错误,,,,转化一下类型
gcc下可以正常编译通过(加上正常的头文件的话)。
student=malloc(sizeof(struct stu));
改成
student=(stu *)malloc(sizeof(struct stu));
student = ( stu* ) malloc ( sizeof ( struct stu ) );
首先 ,只看到了 malloc 没有看到free。student=malloc(sizeof(struct stu)); 这里有问题,应该改为 ,student=(stu*)malloc(sizeof(struct stu));而且没有进行判断,万一内存不够用,无法申请到内存怎么处理。容易造成内存泄露
malloc(sizeof(struct stu)); 之前要加强制类型转换,因为默认malloc分配的指针是void*类型