的C指针算法,而不结构的对象 [英] C pointer arithmetic without object of structure

查看:94
本文介绍了的C指针算法,而不结构的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得是不是在C可能的,但要求验证这一点。是否有可能使结构成员之间的算术没有这种类型的实型变量?例如:

I think it is not possible in C but ask to verify this. Is it possible to make arithmetic between structure members without real variable of this type? For example:

typedef struct _s1
{
  int a;
  int b;
  int c;
} T1;

我想看到的偏移量c的成员相比,结构开始。这是很容易,如果我有变量:

I want to see the offset of "c" member compared to structure beginning. It is easy if I have variable:

T1 str;

int dist = (int)&str.c - (int)&str;

但我的结构过于庞大,它在RAM(仅在EEPROM)没有成员。我想做出一些地址计算而不是定义RAM成员。我可以做结构的指针,而不是结构变量的工作(这将花费只有4个字节),但如此有趣的是我。

But my structure is too big and it has no member in RAM (only in EEPROM). And I want to make some address calculations but not to define RAM member. I can do the job with structure pointer instead of structure variable (it will cost only 4 bytes) but the case is interesting for me.

推荐答案

使用 offsetof 你可以让成员之间的计算,而无需获得该类型的变量举行。所有你需要的是类型本身和成员的名字。

Using offsetof you can make calculations between members without having to get hold of a variable of that type. All you need is the type itself and the name of the member.

一个音符,为什么普通的计算是不容易摸出:数据对齐。你不知道你的填充编译器会在您的结构抛出的数量,这可能导致非常微妙的错误或对其进行正确看似错误的计算,如果你改变了结构。

A note why plain calculations are likely not to work out: data alignment. You do not know the amount of padding your compiler is going to throw at your structure and this can lead to very subtle mistakes or make seemingly correct calculations wrong if you change the structure.

这篇关于的C指针算法,而不结构的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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