C語言基礎知識 ---------- 指標(pointer)、結構(structure)
指標(pointer)
指標變數是一種特殊的變數,此變數儲存的內容不是普通值(int double char......)而是其它變數的地址(address)。
- 指標宣告:資料形態 *變數名 ----> int *ptr 、 char *ptr 、double *ptr ......。
- 取址運算元: &變數名 ----> int score = 85 ; printf( "%d\n" , score ) ; printf( "%p\n" , &score) ; 結果:85 和 00022525FC(score變數在記憶體中存放的地址)。
- 指標賦值:int score = 85 ; int *ptr ; ptr = & score; 即把變數score的地址賦值給了指標變數ptr。
- 取值運算元:*指標變數名 ----> int score = 85 ; int *ptr ; ptr = & score ; printf( "%d" , *ptr ) ; printf( "%p" , ptr ) ; 結果:85 和 00022525FC 。通過*取的指標所指地址的值,可以說 *ptr 就是變數 score;
注意:宣告指標變數時 用的(*) 表示的僅僅是: 此變數為指標沒有其它意思,*後的變數名才是指標的名。 在取值時 用的(*) 是取值運算元,不要弄混。
- 陣列指標: int tests[5] = {71,83,67,49,59} ; int *ptr ; 若直接用陣列名 tests 作為賦值,指向的是陣列的第一個元素地址,tests = & tests[0] ----> ptr = tests 等於 ptr = &tests[0] 。對於陣列指標可以進行加減法:若ptr = &tests[0] ,ptr+2 即指向 &tests[2] ;若ptr = &tests[3] ,ptr-2 即指向 &tests[1] 。
結構(structures)
結構就是自定義一個新的資料型別,有點像java裡的實體類。
- 結構宣告:關鍵字struct,結構中的變數為該結構的成員。
struct student{
int id ; char name[20] ; int score;
}
- 結構變數宣告: 未初始化:struct student std1 ;成員賦值使用 (.):std1.id = 1 ; strcpy(std1.name , "帥哥");std1.score = 90 ;初始化: struct student std2 = { 2 , " 帥哥 " , 90 };
- 結構陣列:struct student stds[3] ; 即有3個 stds[0] 、 stds[1] 、 stds[2] 。
- 結構指標:基本一致,即指標存的是結構變數的地址。但指標型別也必須宣告成結構型別。特殊的是為成員賦值可使用 (->) 符號。
struct student std , *ptr ; ptr = &std ;
有兩種成員賦值方式:ptr -> id = 2 ; (*ptr). score = 90 ;
關鍵字typedef
就是用來為資料形態取別名的。
typedef int B ; ----> B numb = 5 ; 即這裡 B 就是資料形態 int ,是 int 的別名。
- 定義結構時:
struct student{
int a ;
}
typedef struct student Stu ;
為結構取了別名Stu,定義結構變數時:Stu std ; 或 struct student std
typedef struct student{
int a ;
}Stu
這裡Stu就是結構 struct student 的別名,定義結構變數時:struct student std ;或 Stu std ;
student也可以不寫,如:
typedef struct{
int a ;
}Stu
那麼此時定義此結構變數時只能:Stu std ; 這一種表示方式。
常數定義
兩種方式:#define 和 關鍵字 const ;
- ex.1 #define 常數名 值 ---> #define PI 3.1415926
- ex.2 const 資料形態 常數名 = 值 ---> const double PI = 3.14.15926 ;
常數是不可被更改,被賦值。
字串
C語言沒有內建字串資料形態,C語言的字串就是一種char字元形態的一維陣列,並使用 ‘ \0 ’ 標識字串結束。
- char str[15] = "hello! world\n" ;
h | e | l | l | o | ! | w | o | r | l | d | \n | \0 | ||
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
宣告一個字串,有15個元素,“\0”時結束字元,結束字元是佔空間的需要預留一位。用strlen()求某字串長度是不包括“\0”,用sizeof求某字串長度是包含"\0"。輸出格式是%s , printf("字串內容:%s\n",str)。
僅為個人理解,如有不足,請指教。 https://blog.csdn.net/weixin_35811044