结构体指针 分配空间
答案:2 悬赏:60
解决时间 2021-02-03 09:39
- 提问者网友:深爱及嗨
- 2021-02-03 00:10
#include
#include
struct data
{
int day,month,year;
};
struct stu
{
char name[2];
long num;
struct data birthday;
};
main()
{
struct stu *student;
student=(malloc(sizeof(struct stu)));//就是这句有问题,却不知道哪里有问题,和书上的一样啊
scanf("%s",student->name);
scanf("%ld",&student->num);//为什么这里有&,上面一行木有,有什么区别吗
scanf("%d %d %d",&student->birthday.year,&student->birthday.month,&student->birthday.day);//这里不用&有木有关系
printf("\n");
printf("%20s %10ld %d %d %d",student->name,student->num,student->birthday.year,student->birthday.month,student->birthday.day);
}
新手上路,请多多帮忙啊!多谢啦!!
最佳答案
- 二级知识专家网友:迷人小乖乖
- 2021-02-03 01:25
student=(malloc(sizeof(struct stu)));//就是这句有问题,却不知道哪里有问题,和书上的一样啊
malloc出的地址要做一个类型转换。
student = (struct stu *) malloc( sizeof( struct stu));
scanf("%ld",&student->num);//为什么这里有&,上面一行木有,有什么区别吗
上一行name是数组,数组名代表这个数组的首地址。所以已经是地址了。
而num是long型的。所以要取num的地址.
scanf("%d %d %d",&student->birthday.year,&student->birthday.month,&student->birthday.day);//这里不用&有木有关系
必须要&,&这个符号表示取变量的地址。理由和上一条差不多。
全部回答
- 1楼网友:余生继续浪
- 2021-02-03 02:45
假设有以下代码: listnodeptr s; *listnodeptr p=&s; **listnodeptr pp=&p; 假设listnodeptr s在内存中存放的地址为1000,p指向s,pp指向p,示意如下: 1000:s的内容 1005:p的内容=1000 1009:pp的内容=1005 即s的地址是1000,代表结构体的内存位置;p的地址是1005,p的值为1000指向s;pp的地址是1009,p的值为1005指向p(即指针的指针)。 故: 1. listnodeptr s:s就是结构体的代表,并不是结构体指针,p才是结构体指针; 2. *listnodeptr s:这里s才是结构体指针; 3. 传参时,用function_2(&s)或function_2(*s)可直接在函数中访问原结构体内容;用function_1(s)则会将结构体复制一份压到参数栈中,函数中访问的是复制的副本。看实际需要使用。
我要举报
大家都在看
推荐资讯