Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...