[comp.lang.c] pointer arithmetic question

Ray_Gardner@milehi (Ray Gardner) (10/18/87)

I have coded something like this:
struct s {
   char junk1[72];
   long fpos;         /* file pos. of buffer contents */
   int junk2;
   char junk3;
   char buf[4097];
   } *p;              /* pointer to buffer structure */
char *p1;             /* pointer to somewhere in p->buf */
 
  (p1 - p->buf + p->fpos) + 101    <--- is this well-defined?
 
This worked as I expected on a DOS compiler and a UNIX compiler, but 
XENIX on a TI 1100 (an 80286 machine) gave me something different. 
Roughly, the code generated was
   mov   bx,_p          ; pointer to structure

   mov   ax,[bx+72]     ; lsw of p->fpos
   add   ax,_p1         ; add pointer to loc. in p->buf

   sub   ax,_p          ; subtract pointer to structure
   add   ax,22          ; add 22 = 101 - (offset of buf)
   cwd                  ; convert word to double
 
Is the compiler free to make this interpretation?  I cured the problem 
with a cast:
   ((long)(p1 - p->buf) + p->fpos) + 101


---
 * Origin: * Excalibur * Boulder CO * 303-497-6673 (Opus 1:104/39)
SEEN-BY: 104/39 56
--  
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
via FidoNet 104/56 Mile Hi Tech  (303-973-9338)
       uucp:  ...!{hao|isis}!scicom!milehi!oscar

gwyn@brl-smoke.ARPA (Doug Gwyn ) (10/19/87)

In article <0.21787448@milehi> Ray_Gardner@milehi (Ray Gardner) writes:
>I cured the problem with a cast:
>   ((long)(p1 - p->buf) + p->fpos) + 101

The compiler should have done essentially this for you in the first place.
The difference of two pointers within the same aggregate object is some
signed integral type; when that is added to a (long), it should have been
converted to (long) before the addition.