深入理解 C 指標閱讀筆記,深入理解指標
Chapter3.h
#ifndef__CHAPTER_3_#define__CHAPTER_3_/*《深入理解C指標》學習筆記 -- 第三章*//*它們都儲存在棧中的什麼位置?*/void __location_stack_test(int*, int);/*指向常量的指標*/void __constant_pointer_test(const int*, int*);/*指向指標的指標*/void __pointer_to_pointer(int**);/*函數指標的使用方法*/typedef int (*fptr_op)(int, int);int add(int, int);int sub(int, int);int function_pointer_test(fptr_op, int, int);#endif
Chapter3.cpp
#include "Chapter3.h"#include <stdio.h>#include <malloc.h>/*它們都儲存在棧中的什麼位置?*/void __location_stack_test(int* p_test, int test){int test1;printf("test's address is : %x\n", &test);printf("p_test's address is : %x\n", &p_test);printf("test1's address is : %x\n", &test1);/*輸出結果是:test's address is : 29f708p_test's address is : 29f704test1's address is : 29f6f4可以看到,在棧中,函數參數的儲存順序是倒過來的,從最後一個參數存起(棧的地址是從高到低),最後,儲存的才是函數中的局部變數我們從地址中可以看出,函數參數的地址和局部變數之間存在空隙,這裡在棧中儲存的是函數調用的返回地址*/}/*指向常量的指標*//*p_test : 需要指向一個整型量,可以是常量,也可以不是,但是,我們不能在函數內利用解引用修改它test : 必須指向一個非常量,因為,我們可以在函數內利用解引用修改它*/void __constant_pointer_test(const int* p_test, int* test){/*通常,我們寫程式的時候需要保證程式不出現“意外”,不過,通常我們知道這個函數的原型就不會隨便傳一個值給這個函數,這個也是我一般的做法,直到我面試的時候,面試官提醒我,是不是添加一個 const 更好呢?我才明白,這樣做是更加嚴謹的做法*///*p_test = 10;這裡會出現問題,因為指標指向的是常量,不允許賦值操作*test = 10;}/*指向指標的指標*/void __pointer_to_pointer(int** test){/*如果我們修改的是指標,這裡是給指標分配記憶體,那麼,我們必須要傳遞指標的指標*/*test = (int*)malloc(sizeof(int));/*什麼時候應該傳遞指標,什麼時候應該傳遞指標的指標?我的理解是:你想要修改什麼,就傳遞它的地址過去*/}/*函數指標的使用方法*/int add(int a, int b){return a + b;}int sub(int a, int b){return a - b;}/*op : 函數指標類型的參數*/int function_pointer_test(fptr_op op, int a, int b){return op(a, b);}