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

Norman Diamond diamond at jit533.swstokyo.dec.com
Thu Jun 27 21:57:36 AEST 1991


In article <m0jspJY-0001ieC at shiva.reed.edu> minar at reed.edu writes:
>If
>void * p;
>(int *)p++;
>is illegal, how do I do what I mean?

p = (int *)p + 1;

This was already answered earlier.

>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 legal.

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

Huh?  Oh, you mean that the buffer was laid out by some other entity
than your C program.  Yes, C (along with every other language except Ada!)
fails to provide for manipulations of such data.  Actually the Ada syntax
is also non-portable, but there's a standardized way to express that you're
manipulating such things.

>The next best thing is:   *(char *)p   to get the char.
Yes.

>Then, I want to get to the unsigned that's next, so the
>obvious next step is   (char *)p++   ie: increment one character.
p = (char *)p + 1

>Later, I can  (unsigned *)p++  to get past the unsigned.
p = (unsigned *)p + 1

Actually in these cases, you might prefer to declare p as a char * instead
of void *.  Then you can say   p++   and   p += sizeof(int)

>while I'm at it, how do you get the offset of an element of a structure
>the ANSI way?
offsetof()
--
Norman Diamond       diamond at tkov50.enet.dec.com
If this were the company's opinion, I wouldn't be allowed to post it.
Permission is granted to feel this signature, but not to look at it.



More information about the Comp.std.c mailing list