C語言中使用結構體

2021-09-07 01:56:02 字數 948 閱讀 2628

1、先定義結構體

struct stu

char name[20];

long number;

float score[4];

再定義指向結構體型別變數的指標變數:

struct stu *p1, *p2 ;或者

struct stu p1, p2 ;

定義指標變數p 1、p 2,分別指向結構體型別變數。

2、在定義型別的同時定義變數,如

struct studentstudent1, student2;

3、直接定義結構型別變數,如

structstudent1, student2;

注意:

定義的結構體如果是指標,訪問成員時就用「->」如果定義的是結構體變數,訪問成員時就用「.」這個使用方式大家在初學stm32的的時候在庫函式中會遇到的,

4、struct和typedef struct的區別

(1)在c中定義乙個結構體型別要用typedef:typedef structstudent stu; 

在宣告變數的時候就可:stu stu1;(如果沒有typedef就必須用struct student stu1;來宣告)

這裡的stu實際上就是struct student的別名。stu==struct student另外這裡也可以不寫student(於是也不能struct student stu1;了,必須是stu stu1;)

typedef struct stu;    

但在c++裡很簡單,直接structstudent stu1;//stu1是乙個變數  

typedef  struct   student2   stu2;//stu2是乙個結構體型別=structstudent  

使用時可以直接訪問stu1.a 但是stu2則必須先   stu2 s2;    

然後    s2.a=10;

C語言中結構體

struct oursvoid main struct ours o2 01 結構體整體直接賦值的時候,即使字串也可以直接賦值 o1.str o2.str 錯誤,字串不能直接賦值 字串拷貝的方式 sprintf o1.str,02.str strcpy o1.str,o2.str 3.1 第一種情況...

c語言中使用自帶的qsort(結構體排序) 快排

c中沒有自帶的sort函式emm 不過有自帶的qsort函式 其實用法都差不多 只是我經常以為c中有sort 標頭檔案要用 1 include 一定要重新把指標指向的值賦值給乙個node型別,不然比較不了 1 struct nodea n 45 int cmp const void x,const ...

c語言中使用自帶的qsort(結構體排序) 快排

c中沒有自帶的sort函式emm 不過有自帶的qsort函式 其實用法都差不多 只是我經常以為c中有sort 標頭檔案要用 1 include 一定要重新把指標指向的值賦值給乙個node型別,不然比較不了 1 struct nodea n 45 int cmp const void x,const ...