结构体指针算术

发布于 2024-12-23 02:55:31 字数 357 浏览 2 评论 0原文

如何使用指针算术打印结构的特定成员?我有一个有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一直在等你来 2024-12-30 02:55:31

使用 stddef.h 中提供的 offsetof 宏:

#include<stddef.h>

main()
{
    asd foo = {100, 200};
    unsigned char* bar = (void*)&foo;
    printf("%d\n", *(int*)(bar+offsetof(asd, j)));
}

任何其他方法都会遇到填充/对齐问题。

Use the offsetof macro provided in stddef.h:

#include<stddef.h>

main()
{
    asd foo = {100, 200};
    unsigned char* bar = (void*)&foo;
    printf("%d\n", *(int*)(bar+offsetof(asd, j)));
}

Any other way runs into padding/alignment issues.

怎樣才叫好 2024-12-30 02:55:31

指针类型需要正确,以便增量添加正确的大小:

printf("%d",*( ((int*)ptr) +1));

编辑:任何 C 程序员都应该知道,使用指针算术访问结构成员是无用且危险的。无用是因为 -> 操作在访问命名成员时更加简洁和精确,而危险是因为简单地使用指针算术会导致许多问题。然而,指针算术是OP所要求的,所以指针算术就是他得到的。

The pointer type needs to be right so that the increment adds the correct size:

printf("%d",*( ((int*)ptr) +1));

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文