日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

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

作者:物聯(lián)網(wǎng)老王 ? 更新時間: 2022-05-31 編程語言

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

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

運(yùn)行結(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ù)進(jìn)行賦值時必須升級(使用?*取值)。

原文鏈接:https://blog.csdn.net/wangyx1234/article/details/123766488

欄目分類
最近更新