1. 程式人生 > >結構體和結構體指標詳細總結

結構體和結構體指標詳細總結

結構體:結構體也是一種資料型別,在一個結構體中包含了多種型別的資料,比如int,float,char等等。使用結構體可以很好地管理一批有聯絡的資料,使用結構體資料可以提高程式的易讀易寫效能。結構體也是C語言用的較多的型別,小型實時作業系統ucos,當讀其原始碼時,會發現指標結構體和連結串列用的是最多的。所以學好結構體和指標是非常重要的。指標在上兩篇文章中已經系統闡述了一些。

結構體常用的宣告方法 及使用:

例1:

struct classmates

{

char name[20];  //學生姓名

char num[12];  //學生學號

int age;            //學生年齡

}  student[30]; //30名學生

int main

{

   student[0].name = "pite"; //將第1位同學的名字設定為pite

   student[0].num = "2015568512";//設定第一位學生的學號

   student[0].age = 18;// 第一位學生的年齡

}

例2:

struct classmates

{

  char name[20];

  char num[12];

  int age;

}

int main()

{

  struct classmates student;

  student.name = "pite";

  student.num = "2015641133";

  student.age = 18;

}

例3:

typedef struct

{

  char name[20];

  char num[12];

  int age;

} classmates;

int main()

{

   classmates student;

   student.name = "pite";

   student.num = "2015564632";

   student.age = 18;

}

結構體指標的舉例應用:

例: 

  typedef struct 

{

   int age ; 

   int sex ;

}classmates;

int main()

{

  classmates stu[2] = {{18, 1},{18, 2}};

  classmates *p;

  for(p = a; p<a+2; p++)

 {

    printf("%d\n%d", p->age, p->sex);

 }

}

結構體指標記憶體分配問題:

struct classmates 

{

   int i;

   int j;

}

定義一個結構體指標後,比如struct classmates *stu; 由於是一個指標變數,在編譯時並沒有為其分配儲存空間,用sizeof(stu)檢測時,結果是4個位元組,即指標常量的大小(一個地址的大小)。與struct classmates student相比,在定義student這個結構體變數後,系統便分配了8位元組空間給此變數(這個結構體變數的地址就是首個成員的地址)。

對於結構體指標變數,需要用malloch函式分配空間,或者將結構體變數的地址賦予結構體指標。例如:

struct classmates *stu = (struct classmates *)malloc(sizeof(struct classmates));

struct classmates *stu = &student;

以上兩種方法的任何一種,都可為結構體指標分配記憶體空間。

如①所示: int num = sizeof(stu);    // num值為4,地址大小是4位元組

                int num_1 = sizeof(*stu);    //num_1值為8,分配了儲存空間後,有個實際的“指向”,位元組數為兩個int變數所佔位元組總和,即為8個位元組。

如②所示將得到同樣的結果。