so how do I do it? (was Re: call to revolt)

minar at reed.edu minar at reed.edu
Thu Jun 27 15:55:03 AEST 1991


If

void * p;
(int *)p++;

is illegal, how do I do what I mean?

I'm writing some code right now that needs to extract information from a buffer
that contains various types in it. Lets say that there's a chunk of memory that
I *know* first contains a char, then an unsigned. I want to get these values.

The obvious way to do it is
struct foo {
  char c;
  unsigned u;
};

and then (struct foo *)p->c  or (struct foo *)p->u

this is nonportable, as to my understanding, as struct arrangements are not
guaranteed.

The next best thing is:
*(char *)p
to get the char. Then, I want to get to the unsigned that's next, so the
obvious next step is
(char *)p++
ie: increment one character. Later, I can
(unsigned *)p++
to get past the unsigned.

This seems very natural to me. Is it illegal? If it is, what do I do instead?

(if you're curious, the structures I'm dealing with are more like:

struct foo {
  char c[x];
  int i[x];
};

where x is variable at runtime.

I don't have to write this code portably, but I'd like to write it correctly
according to ANSI anyway.

while I'm at it, how do you get the offset of an element of a structure
the ANSI way?

(please send responses to me via mail (or post, too, if you want) - I don't
always get to read news.)



More information about the Comp.std.c mailing list