2

I want to find offset of a structure element. I found some answers which suggested offsetof(structure tag, element) function. However, there are structures which do not have structure tag. For example:

struct {int a;} var;

How to handle these cases?

Thuy Nguyen
  • 353
  • 2
  • 10
  • Does this answer your question? [Finding offset of a structure element in c](https://stackoverflow.com/questions/18749349/finding-offset-of-a-structure-element-in-c) – Tarek Dakhran Mar 13 '20 at 14:14
  • 1
    @TarekDakhran: I checked this question before asking this question. However, I did not think that I can use offsetof() function. But now I understand that I was wrong. – Thuy Nguyen Mar 13 '20 at 14:16
  • @ThuyNguyen - You also completely ignored the answers that don't use `offsetof` at all. – StoryTeller - Unslander Monica Mar 13 '20 at 14:20
  • 1
    That's because you only read the first answer. Check @charlieBurns ' answer. – Roberto Caboni Mar 13 '20 at 14:22
  • 1
    If you already have an instance of the structure, you don't need `offsetof`; `offsetof` works around the problem of being unable to compute offsets when you dont. You can simily do `((char *)&var.a - (char *)&var` to get the offset. – R.. GitHub STOP HELPING ICE Mar 13 '20 at 14:30

2 Answers2

2

If your compiler supports it (i.e. gcc), you can combine it with the typeof operator:

struct {int a, b; } var;
printf("%d\n", offsetof(typeof(var), b));
Ctx
  • 18,090
  • 24
  • 36
  • 51
1

Sorry for not thinking deeply enough before asking. We can simply use offsetof() function as below:

offsetof(struct {int a;}, a)
Thuy Nguyen
  • 353
  • 2
  • 10