C語言中如何獲取函數(shù)內成員的值你知道嗎
C語言中如何獲取函數(shù)內成員的值
引言:函數(shù)作為實現(xiàn) C 程序功能模塊的主要載體,可以將功能的實現(xiàn)細節(jié)封裝在函數(shù)內部。這對于實現(xiàn)模塊化的編程帶來了便利,讓指定功能的復用性也變得更好。但“封裝”除帶來上述好處外,也導致訪問函數(shù)內部細節(jié)的不太方便,為了了解函數(shù)內部的情況,我們討論如何對函數(shù)進行拆包,即獲取函數(shù)內部的信息。
通過函數(shù)返回值獲取函數(shù)內部的情況
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
小結:不管是想獲取指定函數(shù)內指針的值還是變量的值,都可以通過函數(shù)的返回值來獲取函數(shù)內部某一個變量的情況。
通過變量降級(傳地址)獲取函數(shù)內部的情況
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
小結:通過將一個變量降級(即傳遞地址到函數(shù)中,如變量 get_value 將級為1級指針 &get_value,一級指針 ptr1,降級為二級指針 &ptr1,二級指針 ptr2 降級為三級指針 &ptr2 ),作為函數(shù)的形式參數(shù)傳遞到函數(shù)內,然后在函數(shù)內對傳遞的參數(shù)執(zhí)行 升級賦值(升級是指對指針執(zhí)行 * 操作,即上述采取的 *output = ...的寫法),來使得外部的變量獲取到函數(shù)內變量的值。
總結
獲取函數(shù)內部變量的值的方法可以通過:
- 函數(shù)的返回值來獲取。
- 通過形式參數(shù)來獲取,在使用這種方法時,需要注意,傳遞的參數(shù)必須降級(使用
&取地址),并且在函數(shù)內給傳遞的參數(shù)進行賦值時必須升級(使用*取值)。
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
C++ 二維數(shù)組參數(shù)傳遞的實現(xiàn)方法
這篇文章主要介紹了C++ 二維數(shù)組參數(shù)傳遞的實現(xiàn)方法的相關資料,這里提供三種方法幫助大家實現(xiàn)這樣的功能,需要的朋友可以參考下2017-08-08
C++11/14 線程中使用Lambda函數(shù)的方法
這篇文章主要介紹了C++11/14 線程中使用Lambda函數(shù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
基于Sizeof與Strlen的區(qū)別以及聯(lián)系的使用詳解
本篇文章是對Sizeof與Strlen的區(qū)別以及聯(lián)系的使用進行了詳細的介紹。需要的朋友參考下2013-05-05

