Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c++ - C pointer arithmetic without object of structure

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;

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;

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...