本文進行討論的是,在Linux中,C/C++語言的結構體的使用情況。一般情況下,結構體的使用還是相對比較簡單的,它攜帶的一類物體的某一些屬性,
比如
struct person { int age; int height; //... };
這個結構一攜帶的就是一個人的兩個基本信息,年齡(age)和身高(height),同樣你也可以繼續添加人的相關信息進去,比如學號,班級等。
但是今天討論的是在結構體中定義一個結構體指針的問題,當然這也可以延伸到結構體定義一個普通類型的指針方面,讀者可以自行進行驗證或者思考,本文
不作討論。
typedef struct tagStudent_T { int i_StuID; int i_StuClass; }Student_T; typedef struct tagSchool_T { Student_T *student; int i_SchoolRank; }School_T;
上述的兩個結構體表示的含義是:
第一個: 學生的個人信息
第二個:學校的情況(包含了學生的信息和學校的排名)
接下來,如果要對Statuend_T的結構體的變量進行設置,那么有兩種方法,第一個直接使用Student_T定義的變量進行賦值,第二個就是使用School_T進行間接賦值,
今天就是討論第二種的方法。
首先,在一個程序運行過程中,實際上是內存指針在操作,因此我們定義School_T的指針*school,具體的操作如下程序
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> typedef struct tagStudent_T { int i_StuID; int i_StuClass; }Student_T; typedef struct tagSchool_T { Student_T *student; int i_SchoolRank; }School_T; int main(int argc,char const *argv[]) { School_T *school = (School_T *)malloc(sizeof(School_T)); if(NULL != school) { school->i_SchoolRank = 1; //rank first /*由於School_T中定義的student是一個結構體指針,必須要對其進行分配內存*/ school->student = (Student_T *)malloc(sizeof(Student_T)); if(NULL != school->student) { school->student->i_StuID = 12345; school->student->i_StuClass = 5; } else { free(school); } } /*這兩個的free順序最好不要調轉,因為如果先free掉school的話,相當於將student得本體free了,相當於一個野指針 */ free(school->student); free(school); }
如果你不想使用這種方式,大可直接使用變量,不是指針類的變量,如School_T school。同樣School_T結構體重使用的也是一個普通的變量,即Student_T student,這樣,
你就不需要進行內存指針的操作。但是本人建議還是使用指針來進行,效率相對而言會更快一點。可以參考一些<C和指針>這本書
(注:上述的編譯只在Ubuntu下的Linux系統操作,其他的win,vs等沒有進行測試)