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.
int, passint* and deference with*p = ...`. The same is true for pointers.printffunction has a%pformat specifier that you should have a play with to find our where the various things live. It is used the same as%dexcept that it expects avoid*argument (you can use any old pointer). Try pastingprintf("The address of ptr is %p",&ptr);around your code. Try it with other variables too and get some ideas about the memory management. When you use the heap (malloc,free, etc.) you'll find even more memory regions pop up. (Maybe even try passing it a function name, or a label value!)printf, See the answers.%ppointer specifier to see what the other answers said for yourself, so that you can see the difference in the addresses between stack and static variables. Even use it to look at the value contained inptr.