C語言中如何獲取函數內成員的值你知道嗎
C語言中如何獲取函數內成員的值
引言:函數作為實現 C 程序功能模塊的主要載體,可以將功能的實現細節(jié)封裝在函數內部。這對于實現模塊化的編程帶來了便利,讓指定功能的復用性也變得更好。但“封裝”除帶來上述好處外,也導致訪問函數內部細節(jié)的不太方便,為了了解函數內部的情況,我們討論如何對函數進行拆包,即獲取函數內部的信息。
通過函數返回值獲取函數內部的情況
int get_the_value_by_return(int input) { return ++input; } int *get_the_value_by_return2(void) { int *p0 = (int *)malloc(2*sizeof(int)); printf(" p0 = %p\r\n", p0); return p0; } void app_main(void) { printf("init done\r\n"); int i = 1; int get_value = get_the_value_by_return(i); printf("get_value = %d\r\n", get_value); int *ptr0 = get_the_value_by_return2(); printf("ptr0 = %p\r\n", ptr0); free(ptr0); ptr0 = NULL; while (1) { vTaskDelay(1000 / portTICK_PERIOD_MS); } }
上述程序輸出結果:
init done
get_value = 2
p0 = 0x3ffaf814
ptr0 = 0x3ffaf814
小結:不管是想獲取指定函數內指針的值還是變量的值,都可以通過函數的返回值來獲取函數內部某一個變量的情況。
通過變量降級(傳地址)獲取函數內部的情況
void get_the_value_by_addr(int input, int *output) { *output = ++input; } void get_the_value_by_addr1(int **output) { int *p1 = (int *)malloc(2*sizeof(int)); printf(" p1 = %p\r\n", p1); *output = p1; } void get_the_value_by_addr2(void ***output) { int *p2 = (int *)malloc(2*sizeof(int)); printf(" p2_addr = %p\r\n", &p2); *output = &p2; } void app_main(void) { printf("init done\r\n"); int i = 1; int get_value = 0; get_the_value_by_addr(i, &get_value); printf("get_value = %d\r\n", get_value); int *ptr1 = NULL; get_the_value_by_addr1(&ptr1); printf("ptr1 = %p\r\n", ptr1); free(ptr1); ptr1 = NULL; int **ptr2 = NULL; get_the_value_by_addr2(&ptr2); printf("ptr2 = %p\r\n", ptr2); free(*ptr2); ptr2 = NULL; while (1) { vTaskDelay(1000 / portTICK_PERIOD_MS); } }
運行結果:
init done
get_value = 2
p1 = 0x3ffaf814
ptr1 = 0x3ffaf814
p2_addr = 0x3ffb5c60
ptr2 = 0x3ffb5c60
小結:通過將一個變量降級(即傳遞地址到函數中,如變量 get_value 將級為1級指針 &get_value,一級指針 ptr1,降級為二級指針 &ptr1,二級指針 ptr2 降級為三級指針 &ptr2 ),作為函數的形式參數傳遞到函數內,然后在函數內對傳遞的參數執(zhí)行 升級賦值(升級是指對指針執(zhí)行 *
操作,即上述采取的 *output = ...
的寫法),來使得外部的變量獲取到函數內變量的值。
總結
獲取函數內部變量的值的方法可以通過:
- 函數的返回值來獲取。
- 通過形式參數來獲取,在使用這種方法時,需要注意,傳遞的參數必須降級(使用
&
取地址),并且在函數內給傳遞的參數進行賦值時必須升級(使用*
取值)。
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
基于Sizeof與Strlen的區(qū)別以及聯系的使用詳解
本篇文章是對Sizeof與Strlen的區(qū)別以及聯系的使用進行了詳細的介紹。需要的朋友參考下2013-05-05