繁体   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