大家帮我看问题出现在哪

来源:百度知道 编辑:UC知道 时间:2024/07/04 18:59:46
#include <stdio.h>

struct rtc {
char year;
char month;
char day;
};
struct rtc *t,*p;

void set(struct rtc *);
void get(struct rtc *);

int main(void)
{

struct rtc a = {7,8,9};
t = &a;
set(t);
get(p);

printf("%dyear %dmonth %dday\n",t->year,t->month,t->day);
printf("%dyear %dmonth %dday\n",p->year,p->month,p->day);
return 0;
}

void set(struct rtc *t)
{
--t->year;
++t->month;
++t->day;
}

void get(struct rtc *q)
{
struct rtc b = {2,3,4};
q = &b;
}

编译可以通过,第一个printf可以正确输出,第二个printf就不行了,怎么回事啊

void get(struct rtc *q)
{
struct rtc b = {2,3,4};
q = &b;
}
b是临时变量,你用q指向临时变量的地址,你要指向值啊
get调用完之后内存被释放了;
当然不行
void get(struct rtc *q)
{
q->year = 2;
q->month = 3;
q->day = 4;

}
这样可以

void set(struct rtc *t)
{
--t->year;
++t->month;
++t->day;
}
这个函数在传递参数时,形参t是实参t的拷贝,它们的值相同,指向同一内存单元,所以在函数体内对结构体的值修改是有效的。
而void get(struct rtc *q)
{
struct rtc b = {2,3,4};
q = &b;
}
在传递参数是p没有指向任何有效内存单元,传递给q后,p和q的值虽然相同但p和q位于不同的内存单元,改变q的值不会改变p的值,即执行完函数后,p没有指向任何结构体,即使在函数里让p指向了结构体b,而当函数get结束后,b这个局部变量就会消失,p又指向了无效的内存单元