-1

I have to add a piece of code to a big code that already exists. I have a pointer in my code, *Ptr. This pointer is of type, unsigned char.

unsigned char *Ptr;

And I have the below struct.

struct
{
   uint8_t tag;
   uint16_t data[size];
   bool status;
}Test;

Test *TagData;

The pointer is typecasted as below and Now the struct pointer is pointing to the location pointed by the pointer Ptr;

TagData = (Test *)Ptr;

In my code, I will be copying some output values to this structure so that those values get copied to the memory location pointed by *Ptr.

In order to copy some values to the data array in the structure, I need to find the offset to that struct member. I want to do it without using offsetof function. I tried doing the below and I get compiler error.

TagData->data  = (uint16_t *) (Ptr + sizeof(TagData->tag));

Can anyone tell how to do this ? And I don't want to use the offsetof function. Is there a simpler way to do this?

priti
  • 3
  • 1
  • 6
  • 4
    The real question is: why don't you want to use offsetof? You can do it easily by reusing the typical offsetof definition (`(int)(&((type *)0)->member)`). But this probably won't solve your problem, since it is actually the same thing. Now, if it is because you need the offset for non-POD classes and the compiler is complaining, there are usually some intrinsics the compiler provides: e.g. `__builtin_offsetof` for gcc. – dim Feb 06 '17 at 21:52
  • 2
    C only provides the minimum set of functionality. Thus, if there was a standard way, `offsetof` would not have been added to the standard. – too honest for this site Feb 06 '17 at 22:21
  • An even simpler way than using the `offsetof` macro is to use the member in question directly and and use a pointer to the such a member. In 99% of the cases there is no reason at all to play games between integer types and pointers and computing offsets back and forth. Don't do it. You can only get it wrong, it doesn't make your code faster. Pointer casts are evil. – Jens Gustedt Feb 06 '17 at 22:46
  • Why don't you just use `&ptr->data` ??! – user253751 Feb 07 '17 at 03:37
  • `(Test *)Ptr;` This is a bug since it leads to a strict aliasing violation. You invoke undefined behavior. – Lundin Feb 08 '17 at 07:58

1 Answers1

9

No, there's no simpler method than using offsetof, which was designed to do what you need.

Also, offsetof is not a function, but a macro, hiding the pointer arithmetic that you'd do if you didn't use offsetof.

So, clear answer: Since you don't even give a reason, it can't be an overly good reason. Get over it and use offsetof.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94