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

时间:2016-12-06 09:24:28

标签: c pointers

我有一个案例,我需要一个指针变量的地址。变量位于不同的文件中,因此我创建了一个函数并将其传递给指针。该函数将变量的地址分配给指针 但该变量的地址不在指针中更新。 我的代码如下 -

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 个答案:

答案 0 :(得分:2)

第一种方法不起作用,因为您按值传递指针并更新它。在第二种方法中,您通过引用传递它,因此更新的值保持不变。

简单地说,当你按值传递时,调用者和被调用者有2个不同的变量副本,因此被调用者更新的数据不会反映在调用者中。在传递引用时,情况并非如此,更新后的数据会在调用者中反映出来。

答案 1 :(得分:1)

第一版GetAddress(GlobalStruct.ptr);中的来电main() 会更改来电者GlobalStruct.ptr的值。

指针按值传递。

(第二种方法有效,因为当你传递一个指向指针的指针时 更改调用者中GlobalStruct.ptr的值)。

相关问题