结构体指针算术
如何使用指针算术打印结构的特定成员?我有一个有 2 名成员的结构。我想通过操作指向该结构的指针的内存来打印成员j
。
#include <stdio.h>
#include <conio.h>
typedef struct ASD
{
int i;
int j;
}asd;
void main (void)
{
asd test;
asd * ptr;
test.i = 100;
test.j = 200;
ptr = &test;
printf("%d",*(ptr +1));
_getch();
}
How to print a particular member of a structure using pointer arithmetic? I have a structure with 2 members. I want to print out member j
by manipulating the memory of the pointer to that structure.
#include <stdio.h>
#include <conio.h>
typedef struct ASD
{
int i;
int j;
}asd;
void main (void)
{
asd test;
asd * ptr;
test.i = 100;
test.j = 200;
ptr = &test;
printf("%d",*(ptr +1));
_getch();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
stddef.h
中提供的offsetof
宏:任何其他方法都会遇到填充/对齐问题。
Use the
offsetof
macro provided instddef.h
:Any other way runs into padding/alignment issues.
指针类型需要正确,以便增量添加正确的大小:
编辑:任何 C 程序员都应该知道,使用指针算术访问结构成员是无用且危险的。无用是因为
->
操作在访问命名成员时更加简洁和精确,而危险是因为简单地使用指针算术会导致许多问题。然而,指针算术是OP所要求的,所以指针算术就是他得到的。The pointer type needs to be right so that the increment adds the correct size:
Edit: As any C programmer should know, using pointer arithmetic to access struct members is useless and dangerous. Useless because the
->
operation is much more concise and precise in accessing a named member, and dangerous because naive use of pointer arithmetic will result in a number of issues. However, pointer arithmetic is what the OP asked for, so pointer arithmetic is what he got.