R
Rui Maciel
BartC said:Suppose I have these types:
#define byte unsigned char
typedef struct {
int a,b,c,d;
} R; /* assume this is 16 bytes */
R stores 4 objects of type int, whose size is platform-dependent. If you
need a 4-byte integer data type then your best bet would be on int32_t,
which gives you the assurance that you will get an integer data type which
is exactly 32-bit wide.
And these variables:
int n; /* represents a *byte* offset */
If you wish to represent a byte offset then you should use size_t instead.
R* p;
I want to be able to do the following:
p += n;
but it doesn't work because n is a byte offset; it's not in terms of R
objects.
I don't know what yo were trying to do, but if you were trying to access the
offset of a structure member by supplying the address of the struct then you
should use the offsetof() command instead of relying on pointer arithmetic
voodoo.
But the obvious cast:
(byte*)p+=n;
doesn't appear to compile.
Try
The workarounds seem to be:
p += n/sizeof(R);
which I don't like.
You shouldn't. No one should. It represents all kinds of badness.
Even though p is always aligned (and n is known to be
a multiple of 16),
How do you know that p is always aligned, and that n is a multipleof 16?
Each non-bit-field member of a struct is aligned in an implementation-
defined manner, which means that there isn't any guarantee regarding the
alignment of the structure members.
In addition, padding may or may not exist.
Finally, R was defined as a struct composed of 4 objects of type int, and
the int data type may be 8 or 16-bit wide depending on the implementation.
and I know the divide will cancel out, it seems funny
having to introduce a divide op in the first place. And:
p = (R*)((byte*)p+n);
which is what I'm using but looks very untidy in real code.
In any case, the question remains, *is* there a way to cast an lvalue as
I've shown above?
What exactly were you trying to accomplish with that code? It's rather odd
that someone tries to assign a pointer to a structure to the n-th member of
a struct of the same type.
Rui Maciel