結構體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>把結構做爲參數傳遞
相關文章
相關標籤/搜索