C程序:head是全局变量,为什么还要用return来回传呢?

来源:百度知道 编辑:UC知道 时间:2024/05/26 11:02:55
#include "stdio.h"
#include "malloc.h"
struct student
{long i;
char name[10];
int money;
char addr[20];
struct student *next;
}*p1,*p2,*head; /*head是全局变量,为什么下面的del函数还要用return(head)来回传呢*/
main()
{ struct student *del(int num,struct student *head);
int num;
p1=(struct student *)malloc(sizeof(struct student));
head=p1;
scanf("%ld%s%d%s",&p1->i,p1->name,&p1->money,p1->addr);

while(p1->i!=0)
{p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
p2->next=p1;
scanf("%ld%s%d%s",&p1->i,p1->name,&p1->money,p1->addr);
}
p1->next=NULL;
p1=head;
for(;p1->next!=NULL;)
{printf("%ld,%s,%d,%s\n",p1->i,p1->name,p1->money,p1->addr);
p1=p1->next;
}
scanf("%d"

你的理解就错了,
struct student *del(int num,struct student *head) {....}中的head是局部的当它运行完后若不返回就会消失.它与程序开头的head是两个完全不同的变量,如果还不清楚可以去查一下this指针.

由于p1是struct student结构类型函数 也应当返回struct student结构类型值,当del函数运行完后,返回操作过后的head的值(值为内存地址)给p1;
当执行p1=del(num,head)时,把全局head的值(即内存地址)传给局部head,del函数操作局部head指向的内存地址(del函数中的这一步 if(p1==head) head=p1->next 已经把当前局部head的值改掉了(记住head里面放的是内存地址),但它并没有改掉全局head的值),如果没有return(head) 那么for(;p1->next!=NULL;) 操做的是
p1=(struct student *)malloc(sizeof(struct student));
head=p1;
这儿的值而不是del函数运行过后的值

嗯,在del函数中形参head屏蔽了同名的全局变量.

return回去的head是局部变量,是函数的行参