如何通过偏移量获取/设置结构成员 [英] How can I get/set a struct member by offset

查看:36
本文介绍了如何通过偏移量获取/设置结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

忽略填充/对齐问题并给出以下结构,在不使用成员名称的情况下获取和设置 member_b 值的最佳方法是什么.

Ignoring padding/alignment issues and given the following struct, what is best way to get and set the value of member_b without using the member name.

struct mystruct {
    int member_a;
    int member_b;
}
struct mystruct *s = malloc(sizeof(struct mystruct));

换一种方式;您将如何用指针/偏移量表达以下内容:

Put another way; How would you express the following in terms of pointers/offsets:

s->member_b = 3;
printf("%i",s->member_b);

我的猜测是

  • 通过查找 member_a (int) 的大小来计算偏移量
  • 将结构转换为单字指针类型 (char?)
  • 创建一个int指针并设置地址(到*charpointer + offset?)
  • 使用我的 int 指针来设置内存内容
  • calculate the offset by finding the sizeof the member_a (int)
  • cast the struct to a single word pointer type (char?)
  • create an int pointer and set the address (to *charpointer + offset?)
  • use my int pointer to set the memory contents

但是我对转换为 char 类型有点困惑,或者如果像 memset 这样的东西更合适,或者我通常完全错误地处理这个问题.

but I get a bit confused about casting to a char type or if something like memset is more apropriate or if generally i'm aproching this totally wrong.

为任何帮助干杯

推荐答案

您概述的方法大致正确,尽管您应该使用 offsetof 而不是试图自己找出偏移量.我不知道你为什么提到 memset——它将块的内容设置为指定的值,这似乎与手头的问题无关.

The approach you've outlined is roughly correct, although you should use offsetof instead of attempting to figure out the offset on your own. I'm not sure why you mention memset -- it sets the contents of a block to a specified value, which seems quite unrelated to the question at hand.

这里有一些代码来演示它是如何工作的:

Here's some code to demonstrate how it works:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

typedef struct x {
    int member_a;
    int member_b;
} x;

int main() { 
    x *s = malloc(sizeof(x));
    char *base;
    size_t offset;
    int *b;

    // initialize both members to known values
    s->member_a = 1;
    s->member_b = 2;

    // get base address
    base = (char *)s;

    // and the offset to member_b
    offset = offsetof(x, member_b);

    // Compute address of member_b
    b = (int *)(base+offset);

    // write to member_b via our pointer
    *b = 10;

    // print out via name, to show it was changed to new value.
    printf("%d
", s->member_b);
    return 0;
}

这篇关于如何通过偏移量获取/设置结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆