function to point to a global nested stucture
I am having trouble in writing a function which assigns pointer to the address of global nested structure. But i would like that to be done inside a function, not with in main Please help me in writing the function. Thanks in advance
#include "stdio.h"
typedef struct
{
int 开发者_JAVA技巧c;
}code;
typedef code* p_code ;
typedef struct
{
char a;
int b;
code krish;
}emp;
emp Global_Sam;
int main()
{
code tmpcode_krish;
code* pcode_krish;
pcode_krish = &tmpcode_krish;
printf("Goal %p %p \r\n ", &(Global_Sam.krish), &(Global_Sam).krish);
memset(pcode_krish, 0 , sizeof( code));
// pcode_krish = &Global_Sam.krish;
PointNestedStructToPointer(&pcode_krish);
printf("Goal=> both should be same => %p %p \r\n ", &(Global_Sam.krish), pcode_krish);
return 0;
}
Here,
=> pcode_krish = &Global_Sam.krish;
this will point to the global nested structure. But i need to do that inside a function, hence the function, PointNestedStructToPointer
void PointNestedStructToPointer(p_code *dst )
{
dst = &Global_Sam.krish;
}
The above function doesn't reflect the exact address of the global nested structure, i have put prints a verified. Please help
If you want the equivalent of
dst = &src;
Inside a function you have two options:
Pass the address of a pointer to the function:
void doit(code **p) { *p = &src; } // later doit(&pcode_krish);
Return the pointer from the function and do the assignment yourself:
code *doit(void) { return &src; } // later pcode_krish = doit();
Dereference dst
when making the assignment in PointNestedStructToPointer()
:
*dst = &Global_Sam.krish;
精彩评论