在前面認識C中的結構體中我介紹了結構體的基礎知識,下面通過這段代碼來回顧一下:
1 #include<stdio.h>
2 #define LEN 20
3
4 struct Student{ //定義結構體
5 char name[LEN];
6 char address[LEN];
7 int age;
8 };
9
10 int main(int argc, char* argv[])
11 {
12 struct Student s = { //初始化
13 "bluemsun","NENU",25
14 };
15
16 struct Student * p; //定義一個指向結構體的指針
17 p = &s; //為指針賦值
18
19 printf("s.name = %s,s.address = %s,s.age = %d\n",s.name,s.address,s.age);
20 printf("p->name = %s,p->address = %s,p->age = %d\n",p->name,p->address,p->age);
21 }
這是一個比較簡單的例子程序,在結構體Student中我們定義兩個char數組,現在來考慮這樣一個問題。我們在平時需要使用數組的時候都是可以用指針代替數組作為參數使用,那麼在上面的程序中能否用下面這段代碼代替結構體的定義呢?
1 struct new_Student{ //定義結構體
2 char * name;
3 char * address;
4 int age;
5 };
答案是肯定的,但是可能會遇到一些麻煩。考慮下面一段代碼:
1 struct new_Student s1 = {"zhouxy","EFGH",25};
2 struct Student s2 = {"bluemsun","ABCD",26};
這段代碼是正確的。但是想想其中的字符串存儲在哪裡?對於struct Student變量s2來說,字符串存儲在結構內部,這個結構總共分配了40個字節來存儲兩個字符串。然而對於new_Student變量s1來說,字符串是存放在編譯器存儲字符串常量的任何地方。new_Student結構中僅僅是存放了兩個地址而已。所以如果需要一個結構來存放字符串,請使用字符數組成員。那麼是不是采用指針的方式就真的不能完成內存的分配呢?答案是否定的。在這裡我講解了關於C中的函數malloc(),這個函數是可以在運行期動態分配內存的。所以如果能結合在這裡來使用,那就達到了我們的設想了。考慮下面這段代碼:
1 #include<stdio.h>
2 #include<string.h>
3 #include<stdlib.h>
4
5 struct new_Student{ //定義結構體
6 char * name;
7 char * address;
8 int age;
9 };
10
11 int main(int argc, char* argv[])
12 {
13 char str[] = "zhouxy";
14 struct new_Student s1;
15 //分配用來存放名字的內存
16 s1.name = (char*)malloc(strlen(str)+1);
17 //把名字復制到已分配的內存中
18 strcpy(s1.name,str);
19
20 printf("s1.name = %s\n",s1.name);
21 }
上面代碼是正確的,我們用malloc()函數分配存儲空間,然後把字符串復制到新分配的空間。這裡要理解的是:name字符串不是被存儲在結構中,而是被保存在由malloc()函數管理的內存中。結構中僅僅是保存了name字符串的地址而已。還有一點要記得的是:我們使用malloc()函數分配內存之後要調用free()函數,不然可能會引起"內存洩露"。