[英]Accessing pointer member data of struct
I am trying to access the data of a pointer that is a member of a struct. 我正在尝试访问作为结构成员的指针的数据。
typedef struct
{
int i1;
int* pi1;
} S;
int main()
{
S s1 = { 5 , &(s1.i1) };
printf("%u\n%u\n" , s1.i1 , s1.pi1 ); //here is the problem
return 0;
}
The problem lies in the second argument of printf. 问题出在printf的第二个参数上。 When i run the program i get the following result in console: 5 ...(next line) 2381238723(it's different every time).
当我运行该程序时,我在控制台中得到以下结果:5 ...(下一行)2381238723(每次都不同)。 This is correct, and the result is not unexpected.
这是正确的,并且结果并非意外。 I have tried things like:
我已经尝试过类似的事情:
*(s1.pi1)
and 和
s1.*pi1
None of them works. 它们都不起作用。 Is there any operator in C or method to do this?
在C或方法中是否有任何运算符可以做到这一点?
I'm guessing here, but I think you might have meant to do the following: 我在这里猜测,但我想您可能打算执行以下操作:
typedef struct
{
int i1;
int* pi1;
} S;
int main()
{
// Take the address of s1.i1, not s1.pi1
S s1 = { 5 , &(s1.i1) };
// Dereference s1.pi1
printf("%u\n%u\n" , s1.i1 , *s1.pi1 );
return 0;
}
Going through godel9 's suggestion and comments, I infer that you have found a way to get the expected results 通过godel9的建议和评论,我推断您已经找到一种获得预期结果的方法
You wrote: I have tried things like: 您写道:我已经尝试过类似的事情:
*(s1.pi1)
and s1.*pi1
*(s1.pi1)
和s1.*pi1
I sense a li'l confusion there. 我在那儿感觉有点困惑。
mystruct.pointer
means that you have access to the pointer, now give,take,compare.. address. mystruct.pointer
意味着您可以访问该指针,现在给出,获取,比较..地址。
*(mystruct.pointer)
means that you have dereferenced the pointer,now giv, take,increment.. value. *(mystruct.pointer)
表示您已经取消引用了指针,现在给出了giv,take,increment ..值。
Remember that pointers are just variables which store addresses( ! ) but more versatile than the common ones. 请记住,指针只是存储地址( ! )的变量,但比普通的指针具有更多的用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.