最近在学结构,学完后就想随便编个学生列表。
结果不编还好,一编吓一跳,直接头疼了一个上午。
最后让人啼笑皆非的事情是.....
#include<stdio.h>
struct test{
char name[20];
int number;
double mark;
};
struct test* input(void);
void show(struct test*);
int main(void)
{
show(input());
}
struct test* input(void)
{
struct test list[2];
struct test* ptr=list;
for(int i=0;i<2;i++,ptr++) //我也是真敢写啊
{
scanf("%s",ptr->name);
scanf("%d",&ptr->number);
scanf("%lf",&ptr->mark);
}
return ptr; //我已经无语了
}
void show(struct test* ptr)
{
for(int i=0;i<2;i++,ptr++)
{
printf("%s %d %.2lf\n",ptr->name,ptr->number,ptr->mark);
}
}
相信大家已经就看出来了.....就是这个离谱的地方
实在是蚌埠住了
//-------------------------------------------//
修改过后(还没完呢)
#include<stdio.h>
struct test{
char name[20];
int number;
double mark;
};
struct test* input(void);
void show(struct test*);
int main(void)
{
show(input());
}
struct test* input(void)
{
struct test list[2];
struct test* ptr=list;
for(int i=0;i<2;i++)
{
scanf("%s",(ptr+i)->name);
scanf("%d",&(ptr+i)->number);
scanf("%lf",&(ptr+i)->mark);
}
return ptr;
}
void show(struct test* ptr)
{
for(int i=0;i<2;i++,ptr++)
{
printf("%s %d %.2lf\n",ptr->name,ptr->number,ptr->mark);
}
}
问题又又又又来了!!!!!!!
这一波是真的给我整窒息了
这是个啥???
然后我尝试在两个函数里都取了地址
???
这不是一样的地址吗?还错???
然后我接着两次使用ptr->name
接下来的结果更是给我整懵逼了
这到底是啥??????????
在我百思不得其解之际,我突然想起......我这个结构是在函数内部定义的!!!!
我这一返回指针,结构就销毁了!!!
所以指了半天,指到了个p!
#include<stdio.h>
struct test{
char name[20];
int number;
double mark;
};
struct test* input(struct test list[2]);
void show(struct test*);
int main(void)
{
struct test list[2];
show(input(list));
}
struct test* input(struct test list[2])
{
// struct test list[2];
struct test* ptr=list;
for(int i=0;i<2;i++)
{
scanf("%s",(ptr+i)->name);
scanf("%d",&(ptr+i)->number);
scanf("%lf",&(ptr+i)->mark);
}
printf("\nptr=%p\n",ptr);
return ptr;
}
void show(struct test* ptr)
{
printf("\nptr=%p\n",ptr);
for(int i=0;i<2;i++,ptr++)
{
printf("%s %d %.2lf\n",ptr->name,ptr->number,ptr->mark);
}
}
运行结果
真是两行泪啊。。。。