最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C語言中如何獲取函數(shù)內(nèi)成員的值你知道嗎

 更新時間:2022年03月28日 10:10:07   作者:物聯(lián)網(wǎng)老王  
這篇文章主要為大家詳細介紹了C語言中如何獲取函數(shù)內(nèi)成員的值的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

C語言中如何獲取函數(shù)內(nèi)成員的值

引言:函數(shù)作為實現(xiàn) C 程序功能模塊的主要載體,可以將功能的實現(xiàn)細節(jié)封裝在函數(shù)內(nèi)部。這對于實現(xiàn)模塊化的編程帶來了便利,讓指定功能的復(fù)用性也變得更好。但“封裝”除帶來上述好處外,也導(dǎo)致訪問函數(shù)內(nèi)部細節(jié)的不太方便,為了了解函數(shù)內(nèi)部的情況,我們討論如何對函數(shù)進行拆包,即獲取函數(shù)內(nèi)部的信息。

通過函數(shù)返回值獲取函數(shù)內(nèi)部的情況

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);
    }
}

上述程序輸出結(jié)果:

init done
get_value = 2
 p0 = 0x3ffaf814
ptr0 = 0x3ffaf814

小結(jié):不管是想獲取指定函數(shù)內(nèi)指針的值還是變量的值,都可以通過函數(shù)的返回值來獲取函數(shù)內(nèi)部某一個變量的情況。

通過變量降級(傳地址)獲取函數(shù)內(nèi)部的情況

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);
    }
}

運行結(jié)果:

init done
get_value = 2
 p1 = 0x3ffaf814
ptr1 = 0x3ffaf814
 p2_addr = 0x3ffb5c60
ptr2 = 0x3ffb5c60

小結(jié):通過將一個變量降級(即傳遞地址到函數(shù)中,如變量 get_value 將級為1級指針 &get_value,一級指針 ptr1,降級為二級指針 &ptr1,二級指針 ptr2 降級為三級指針 &ptr2 ),作為函數(shù)的形式參數(shù)傳遞到函數(shù)內(nèi),然后在函數(shù)內(nèi)對傳遞的參數(shù)執(zhí)行 升級賦值(升級是指對指針執(zhí)行 * 操作,即上述采取的 *output = ...的寫法),來使得外部的變量獲取到函數(shù)內(nèi)變量的值。

總結(jié)

獲取函數(shù)內(nèi)部變量的值的方法可以通過:

  • 函數(shù)的返回值來獲取。
  • 通過形式參數(shù)來獲取,在使用這種方法時,需要注意,傳遞的參數(shù)必須降級(使用 &取地址),并且在函數(shù)內(nèi)給傳遞的參數(shù)進行賦值時必須升級(使用 *取值)。

 本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!   

相關(guān)文章

最新評論

林口县| 武定县| 临颍县| 客服| 黄龙县| 二连浩特市| 新野县| 崇左市| 东城区| 乌恰县| 梁河县| 永兴县| 丁青县| 雷州市| 吴江市| 彭阳县| 阳原县| 盐山县| 沭阳县| 安康市| 咸宁市| 东安县| 河北区| 乌拉特中旗| 漳平市| 景洪市| 明溪县| 南木林县| 湖南省| 山西省| 资中县| 成武县| 葫芦岛市| 遂宁市| 吉木萨尔县| 故城县| 平舆县| 云龙县| 新河县| 陆川县| 逊克县|