Pointer and integer addition

Will Crowder willcr at bud.sos.ivy.isc.com
Sat Mar 30 03:32:50 AEST 1991


In article <8334 at umd5.umd.edu>, dzoey at 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 at ivy.isc.com)         |  setting #2?"
INTERACTIVE Systems Corp.    |		-- Guinan



More information about the Comp.lang.c mailing list