結構和其他資料形式
1.結構的樣子:
struct student{
char name[20];
char number[20];
int n;
double value;
};
int main()
{
struct student p1,p2;
...
return 0;
}
- 結構體的宣告
??結構體是由關鍵字struct 來宣告的,它就像是一個模板,里面封裝了相應的資料, - 訪問結構成員
??其中p1、p2都是point里面有name[ ]、number[ ]、n、value的值,
用變數訪問結構成員,用.來呼叫,如:p1.n、p2.value、p1.name[ i ]等, - 還可以宣告結構陣列
struct student{
char name1[25],name4[25],name3[25],name2[25];
};
int main()
{
struct student a[100];
for(int i=0; i<10; i++){
scanf("%s %s %s",a[i].name1,a[i].name2,a[i].name3);
}
for(int i=10-1; i>=0; i--){
printf("%s %s %s\n",a[i].name1,a[i].name2,a[i].name3);
} //逆序輸出
return 0;
}
輸入樣例:?zhangsan haha 01
??????lisi haha 02
??????wangwu haha 03
輸出樣例:?wangwu haha 03
??????lisi haha 02
??????zhangsan haha 01
2.結構指標:
宣告和初始化結構指標:
#include <stdio.h>
struct names {
char first[100];
char last[100];
};
struct guy {
struct names handle; //嵌套結構:結構中包含了另一個結構
char favfood[100];
char job[100];
float income;
};
int main()
{
struct guy fellow[2] = {
{{"Ewen", "Villard" },
"grilled salmon",
"personality coach",
68112.00
},
{{ "Rodney", "Swillbelly" },
"tripe",
"tabloid editor",
432400.00
}
};
struct guy *him; //指向結構的指標
printf("adress #1: %p #2: %p\n",&fellow[0], &fellow[1]);
him = &fellow[0]; //告訴編譯器該指標指向何處
printf("pointer #1: %p #2: %p\n",him, him + 1);
printf("him->income is $%.2f: (*him).income is $%.2f\n",
him->income, (*him).income);
him++; //指向下一個結構
printf("him->favfood is %s: him->handle.last is %s\n",
him->favfood, him->handle.last);
return 0;
}
該程式的輸出結構如下:
adress #1: 0x7fff5fbff820 #2: 0x7fff5fbff874
pointer #1: 0x7fff5fbff820 #2: 0x7fff5fbff874
"him->income is $68112.00: (*him).income is $68112.00
him->favfood is tripe: him->handle.last is Swillbelly
struct guy *him;
??首先是關鍵字struct,其次是結構標記guy,然后是一個星號‘ * ’,其后跟著指標名,這個語法和其他指標宣告一樣,
??該宣告并未創建一個新的結構,但是指標him現在可以指向任意現有的guy型別的結構,例如,如果barney是guy型別的結構變數,可以這樣寫:
him = &barney;
??和陣列不同的是,結構變數名并不是結構變數的地址,因此要在結構變數名前面加上&運算子,
??在本例中,fellow是一個結構陣列,這意味著fellow[0]是一個結構,所以,要讓him指向fellow[0],可以這么寫:
him = &fellow[0];
多說無益,通過這道題可以充分理解結構體指標聯系函式的運用: https://pintia.cn/problem-sets/1337734387166953472/problems/1337735292742037504.
3.鏈式結構
??結構的一個重要用途就是創建新的資料形式,有很多的一些資料結構可以更有效的解決一些特定的問題,資料結構如:佇列、二叉樹、堆、哈希表、圖示,很多資料結構都是鏈式結構,即每個結構都包含一兩個資料項和一兩個指向同型別結構的指標,
4.列舉型別
??可以用列舉型別宣告符號型別來表示整型常量,用關鍵字enum,enum常量是int型別的,列舉型別的用途是在某些時候提高程式的可讀性,
enum spectrum {red, orange, yellow, green, blue, violet};
enum spectrum color;
實際上red、orange都是int型別的常量,red=0,后面的都逐個遞增,
也可以為列舉常量指定整數值,
enum levels{low=100, medium=500, high= 2000};
5.typedef 簡介
??typedef用于為某一特定型別定義別名,用法很簡單,
typedef unsigned char BYTE;
??可以用typedef來為結構命名,此時可以省略結構標簽:
typedef struct {
float imag;
float real;
} COMPLEX;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/237968.html
標籤:區塊鏈
下一篇:Go語言結構體
