evan@plx.UUCP (Evan Bigall) (05/09/89)
This works on my machine, but I am curious as to whether it is "officially"
correct and portable C. I can think of some machines where it could be trouble
main()
{ int array[10], *ptr, j;
for(j=0; j<10; j++)
array[j]=j;
ptr= &array[1];
for(j= -1; j<9; j++)
printf("%d\n", ptr[j]);
}
This is a contrived example, in context it makes a lot more sense.
Evan
kemnitz@mitisft.Convergent.COM (Gregory Kemnitz) (05/10/89)
In article <1914@plx.UUCP>, evan@plx.UUCP (Evan Bigall) writes:
. This works on my machine, but I am curious as to whether it is "officially"
. correct and portable C. I can think of some machines where it could be trouble
.
. main()
. { int array[10], *ptr, j;
.
. for(j=0; j<10; j++)
. array[j]=j;
.
. ptr= &array[1];
.
. for(j= -1; j<9; j++)
. printf("%d\n", ptr[j]);
. }
.
From page 94 of K&R:
If pa points to a particular element of an array a, then by definition pa+1
points to the next element, and in general pa-i points i elements before pa
and pa+i points i elements after.
(end of quote).
Greg Kemnitz
gwyn@smoke.BRL.MIL (Doug Gwyn) (05/10/89)
In article <1914@plx.UUCP> evan@plx.UUCP (Evan Bigall) writes: >This works on my machine, but I am curious as to whether it is "officially" >correct and portable C. The pointer arithmetic was okay; ptr[-1] is legal. (The program failed to #include <stdio.h> and return a value from main(), however.)
visinfo@ethz.UUCP (VISINFO Moderators) (05/12/89)
In Article 15145 of comp.lang.c Evan writes >This works on my machine, but I am curious as to whether it is "officially" >correct and portable C. I can think of some machines where it could be >trouble > > main() > { int array[10], *ptr, j; > > for(j=0; j<10; j++) > array[j]=j; > > ptr= &(array[1]); > > for(j= -1; j<9; j++) > printf("%d\n", ptr[j]); > } I suppose this to be (rather) portable, 'cause the compiler takes the adress of 'ptr', adds j*sizeof(int) and writes out the content of the memory location this pointer is pointing to. So when K&R says : pointer+int is OK : , let us use it. Just imagine the following source (travelling in a string): { char c[]= "abc"; char *runner; runner=&(c[2]); while (runner!=c) runner--; } I see no dangers in it (it's just another way to confuse any kind of range- checking facility) ! Tony