簡體   English   中英

使用C中的函數獲取指針中變量的地址

[英]Getting address of a variable in pointer using function in C

我有一個案例,我需要一個指針變量的地址。 變量位於不同的文件中,因此我創建了一個函數並將其傳遞給指針。 該函數將變量的地址分配給指針。
但該變量的地址不在指針中更新。 我的代碼如下 -

typedef struct
{
    int* ptr;
} test;

int sGlobalVar = 10;
test GlobalStruct; //Create instance of struct


//This function address of Global variable to passed pointer
void GetAddress(int* ptr)
{
   ptr = &sGlobalVar;
   //Prints correct value
   printf("Value of Global Variable in Function %d\n", *ptr);
}


int main()
{

    printf("Hello World!!");
    GetAddress(GlobalStruct.ptr);

    // CODE CRASHES HERE. Because GlobalStruct.ptr is NULL
    printf("Value of Global Variable in Main %d \n", *GlobalStruct.ptr);

    return 0;
}

我做的下一件事是修改我的函數GetAddress(),使它接受指向指針的指針。

//This function address of Global variable to passed pointer
void GetAddress(int** ptr)
{
   *ptr = &sGlobalVar;
   //Prints correct value
   printf("Value of Global Variable in Function %d\n", **ptr);
} 

和主要的

 int main()
    {

        printf("Hello World!!");
        GetAddress(&GlobalStruct.ptr);

        //Now Value prints properly!!
        printf("Value of Global Variable in Main %d \n", *GlobalStruct.ptr);

        return 0;
    }

我很無能為什么第一種方法不起作用。

第一種方法不起作用,因為您按值傳遞指針並更新它。 在第二種方法中,您通過引用傳遞它,因此更新的值保持不變。

簡單地說,當你按值傳遞時,調用者和被調用者有2個不同的變量副本,因此被調用者更新的數據不會反映在調用者中。 在傳遞引用中,情況並非如此,更新的數據反映在調用者中。

調用GetAddress(GlobalStruct.ptr); main()的第一個版本中, 不會更改調用GlobalStruct.ptr的值。

指針按值傳遞。

(第二種方法有效,因為在向指針傳遞指針時,在調用者更改GlobalStruct.ptr的值)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM