1. 程式人生 > >C語言-指針深度分析

C語言-指針深度分析

char float 指針常量 指向 需要 std style 不可 參數

1、變量回顧

程序中的變量只是—段存儲空間的別名,那麽是不

必須通過這個別名才能使用這段存儲空間?

2、思考

下面的程序輸出什麽?為什麽?

1 int i = 5;   
2 int* p = &i;   
3   
4 printf("%d, %p\n", i, p);  
5    
6 *p = 10;   
7   
8 printf("%d, %p\n", i, p);   

3、*號的意義

  在指針聲明時,*號表示所聲明的變量為指針

  在指針使用時,*號表示指針所指向的內存空間中的

*相當於一把鑰匙,通過這把鑰匙打開內存,讀取內存中的值。

4、實例分析

 1 #include <stdio.h>  
 2   
 3 int main()  
 4 {  
 5     int i = 0;  
 6     int* pI;  
 7     char* pC;  
 8     float* pF;  
 9       
10     pI = &i;  
11       
12     *pI = 10;  
13       
14     printf("%p, %p, %d\n", pI, &i, i);  
15     printf("%d, %d, %p\n", sizeof(int
*), sizeof(pI), &pI); 16 printf("%d, %d, %p\n", sizeof(char*), sizeof(pC), &pC); 17 printf("%d, %d, %p\n", sizeof(float*), sizeof(pF), &pF); 18 19 return 0; 20 }

5、傳值調用與傳址調用

  指針是變量,因此可以聲明指針參數

  當—個函數體內部需要改變實參的值,則需要使用指針參數 (★)

  函數調用時實參值將復制到形參

  指針適用於復雜數據類型作為參數

的函數中

6、編程實驗

利用指針交換變量 26-2.c

 1 #include <stdio.h>  
 2   
 3 int swap(int* a, int* b)  
 4 {  
 5     int c = *a;  
 6       
 7     *a = *b;  
 8       
 9     *b = c;  
10 }  
11   
12 int main()  
13 {  
14     int aa = 1;  
15     int bb = 2;  
16       
17     printf("aa = %d, bb = %d\n", aa, bb);  
18       
19     swap(&aa, &bb);  
20       
21     printf("aa = %d, bb = %d\n", aa, bb);  
22       
23     return 0;  
24 }  

7、常量與指針

常量指針p可變,p指向的內容不可變

- const int* p;

- int const* p;

指針常量p不可變,p指向的內容可變

- int* const p;

*p與p均為常量

- const int* const p; //p和p指向的內容都不可變

8、實例分析

常量與指針 26-3.c

 1 #include <stdio.h>  
 2   
 3 int main()  
 4 {  
 5     int i = 0;  
 6       
 7     const int* p1 = &i;  
 8     int const* p2 = &i;  
 9     int* const p3 = &i;  
10     const int* const p4 = &i;  
11       
12     *p1 = 1;    // compile error  
13     p1 = NULL;  // ok  
14       
15     *p2 = 2;    // compile error  
16     p2 = NULL;  // ok  
17       
18     *p3 = 3;    // ok  
19     p3 = NULL;  // compile error  
20       
21     *p4 = 4;    // compile error  
22     p4 = NULL;  // compile error  
23       
24     return 0;  
25 }  

9、小結

指針是C語言中一種特別的變量

指針所保存的值是內存的地址

可以通過指針修改內存中的任意地址內容

C語言-指針深度分析