简体   繁体   中英

Getting address of a variable in pointer using function in C

I have a case that I need address of a variable in a pointer. The variable is located in different file, hence I created a function and passing it a pointer. The function assigns address of variable to pointer.
But address of that variable in not updating in pointer. My code is as follows --

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

Next thing I did is modified my function GetAddress() such that it accepts pointer to pointer.

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

and main as

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

I am clueless why First method is not working.

The first method doesn't work as you are passing the pointer by value and updating it. In the second method you are passing it by reference, so the value updated stays.

To put it simply, when you do a pass by value, the caller and callee have 2 different copies of the variable, so data updated by the callee is not reflected in the caller. Whereas in pass-by-reference, this is not the case, the data updated reflects in the caller.

The call GetAddress(GlobalStruct.ptr); in the first version of main() does not change the value of GlobalStruct.ptr in the caller.

The pointer is passed by value.

(The second way works since you are changing the value of GlobalStruct.ptr in the caller as you are passing a pointer to the pointer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM