结构体1(嵌套使用)

1.结构体嵌套
<1>指向结构体的指针:struct student *p;  struct student student1;    p=&student1;    
访问结构体变量成员的方式:p->age;(*p).age;sudent1.age;
 
<2>一个结构体做另一个结构体的成员
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct item
{
 char first[10];
 char last[10];
 int grade;
}Item;
typedef struct node
{
 Item item;
 struct node *next;
}Node;
 
void main()
{
 Node *node;
 node = (Node *)malloc(sizeof(Node));
 
 //scanf("%s,%s,%d",item1.first,item1.last,&(item1.grade));
 scanf("%s",node->item.first);
 scanf("%s",node->item.last);
 scanf("%d",&(node->item.grade));
 printf("%s,%s,%d\n",node->item.first,node->item.last,node->item.grade);
}
 
<3>一个结构体指针做另一个结构体的成员
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct item
{
 char first[10];
 char last[10];
 int grade;
}Item;
typedef struct node
{
 Item *item;
 struct node *next;
}Node;
 
void main()
{
 Item *item;
 Node *node;
 item = (Item *)malloc(sizeof(Item));
 node = (Node *)malloc(sizeof(Node));
 
 node->item = item;
 gets(node->item->first);
 gets(node->item->last);
 scanf("%d",&(node->item->grade));
 printf("%s,%s,%d\n",node->item->first,node->item->last,node->item->grade);
}
 
注意:
<1>不能将结构体变量作为一个整体输入,输出,只能对其各个成员进行;
<2>允许将一个结构体变量赋给另一个用类型的结构体变量: student1=student2;       
<3>结构体数组与数组不一样,一个结构的名字不是该结构的地址。
<4>建立链表时,main()里的Queue queue;不要定义为指针,若要定义为指针,须为其分配存储空间。
或者传递指针的指针(最好不用这种),否则不能改变指针的值。
 
 
3.用指针处理链表:struct student {int num;float score;stuct student *next; };
处理动态链表所需函数:头文件stdlib.h中有malloc()free()的原型
void * malloc (unsigned int size);
//在动态存储区中分配一个长度为size的连续空间,此函数的值是一个分配域的起始地址(类型为 void)。如果函数为能成功执行则返回null;
void *calloc(unsigned n,unsinged size);
//在动态存储区中分配n个长度为size的连续空间,此函数的值是一个分配域的起始地址。如果函数为能成功执行则返回null;用calloc函数可以为一维数组开辟动态存储空间。
void free(void *p) ;//释放由p指向的动态存储区,p是最近一次调用malloc或calloc时返回的值。
ptr=(int *)malloc(n*sizeof(int));n为一变量,C99之前允许,返回一指向int型的ptr=(int *)calloc(100,sizeof(int));
 
4.向函数传递结构信息
<1>传递结构成员
<2>使用结构地址
<3>把结构作为参数传递
   
posted @ 2014-09-25 16:42  suo_suo  阅读(4729)  评论(0编辑  收藏  举报