Newsgroups: comp.lang.c Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!ispd-newsserver!ism.isc.com!bud.sos.ivy.isc.com!willcr From: willcr@bud.sos.ivy.isc.com (Will Crowder) Subject: Re: Pointer and integer addition Message-ID: <1991Mar29.173250.14745@ism.isc.com> Sender: usenet@ism.isc.com (Ism Usenet News) Reply-To: willcr@ism.isc.com Organization: Interactive Systems Corp. References: <8334@umd5.umd.edu> Date: Fri, 29 Mar 1991 17:32:50 GMT In article <8334@umd5.umd.edu>, dzoey@terminus.umd.edu (Joe Herman) writes: |> Hello, I have a section of code that scans through a block of variable |> length records. The structure looks more or less like this: |> |> struct foo { |> unsigned short recsize; |> unsigned short num; |> char info [24]; |> byte flags; |> char filename[1] |> }; |> |> Where, foo.filename is a placeholder for a variable length string. |> |> After I process one record, I'd like to just increment the pointer to |> point to the next record. What I'd like to do is: |> |> fooptr += fooptr->recsize; |> |> However, the compiler I'm using increments the pointer by |> recsize * sizeof (struct foo). This is probably correct. Indeed, that is the correct behavior. |> Next, I tried |> |> fooptr = (char *) fooptr + fooptr->recsize; |> |> No difference, so I guess it gets the value to multiply the increment from |> the lvalue. I'm surprised that there was no difference here. The cast of fooptr to (char *) in the expression should have behaved as you expected. Both Sun CC and gcc do what you want here, although both issue a warning about assignments between incompatible pointer types. To quiet the warning and make it clear what you are doing: fooptr = (struct foo *)((char *)fooptr + fooptr->recsize); However, there are other potential pitfalls here having to do with data alignment restrictions. If struct foo needs to be aligned on a particular boundary, then you can get into trouble adding non (sizeof struct foo)-sized chunks to the pointer. (The addition will succeed, or should, but you may get an alignment exception on your next access via fooptr.) |> Thanks, |> Joe Herman |> You're welcome. Hope this helps. OBTW, your compiler may be broken. Which one is it? Will -------------------------------------------------------------------------------- Will Crowder, MTS | "That was setting #1. Anyone want to see (willcr@ivy.isc.com) | setting #2?" INTERACTIVE Systems Corp. | -- Guinan