本文介绍了间接访问结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 这是代码 int main(){ struct node { int a; int b; int c; }; struct node s = {3,5,6}; struct node * ptr =& s; printf("%d",*(int *)ptr); } 最后的printf是否总能产生正确的输出?以这种方式访问​​数据成员是否更安全?Here is the codeint main(){struct node{int a;int b;int c;};struct node s={3,5,6};struct node *ptr=&s;printf("%d",*(int*)ptr);}Will the last printf always result in correct output? Is it safer toaccess data members of structure this way?推荐答案 您可以保证结构的第一个元素的地址 始终位于结构的地址,因此您可以安全地访问 你的结构成员''a''(如果它是个好主意是 a完全不同的问题)。对于其他成员来说,它不安全, 例如 printf("%d",*(int *)((char *) ptr + sizeof(int))); 不保证打印出存储在成员中的值 ''b''自编译器以来允许在结构成员之间插入尽可能多的填充字节 。 问候,Jens - \ Jens Thoms Toerring ___ jt@toerring.de \ __________________________ http://toerring.de 为什么不只是使用一个阵列而不是发明复杂的方法来自己拍摄 脚? 问候, Bart。Why not just use an array instead of inventing convoluted ways to shootyourself in the foot?Regards,Bart. 是的,对于第一个成员。结构的第一个成员必须始终具有与结构本身相同的地址。这是标准要求的。 对于任何其他成员,你都不知道。在a和b之间可能有填充 ,所以((int *)& s)+1可能不会指向sbYes, for the first member. The first member of a struct must always havethe same address as the struct itself. This is required by the Standard.For any other member, you don''t know that. There could be paddingbetween a and b, so ((int *)&s)+1 might not point at s.b. 完全没有。正常访问它们是最好的方法。 RichardNot at all. Accessing them normally is the best way.Richard 这篇关于间接访问结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 08:05
查看更多