简体   繁体   English

使用C中的函数获取指针中变量的地址

[英]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. 我做的下一件事是修改我的函数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);
} 

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. 简单地说,当你按值传递时,调用者和被调用者有2个不同的变量副本,因此被调用者更新的数据不会反映在调用者中。 Whereas in pass-by-reference, this is not the case, the data updated reflects in the caller. 在传递引用中,情况并非如此,更新的数据反映在调用者中。

The call GetAddress(GlobalStruct.ptr); 调用GetAddress(GlobalStruct.ptr); in the first version of main() does not change the value of GlobalStruct.ptr in the caller. main()的第一个版本中, 不会更改调用GlobalStruct.ptr的值。

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). (第二种方法有效,因为在向指针传递指针时,在调用者更改GlobalStruct.ptr的值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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