Re: pointer-in-array test
In article <1133145.9pkQ6i reiI@holzmayer. ifr.rt> holzmayer.bernh ard@deadspam.co m writes:
....[color=blue]
> What about this solution:
> int ptrInArrSafe(T *p,T *a,int max)
> /* check whether p points to an element of a[max] */
> {
> long px = (long)p;
> long ax = (long)a;
> if (px<ax) return 0; /*out*/
> if (px> (long)&a[max-1]) return 0; /* out */
> if ( (px-ax) % sizeof(T)) return 0; /* not at element start*/
> return 1; /* in and on element start */
> }
>
> compiles, links, runs without problems with my gcc.
> And, as far as I remember, it's legal, to compare pointers after
> conversion to long.[/color]
But the result is implementation defined. I know of at least one
system where it will fail to give the correct answer, then T is char.
For instance:
(long)(a + 7) > (long)(a + 8)
when a is an array of type char.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
In article <1133145.9pkQ6i reiI@holzmayer. ifr.rt> holzmayer.bernh ard@deadspam.co m writes:
....[color=blue]
> What about this solution:
> int ptrInArrSafe(T *p,T *a,int max)
> /* check whether p points to an element of a[max] */
> {
> long px = (long)p;
> long ax = (long)a;
> if (px<ax) return 0; /*out*/
> if (px> (long)&a[max-1]) return 0; /* out */
> if ( (px-ax) % sizeof(T)) return 0; /* not at element start*/
> return 1; /* in and on element start */
> }
>
> compiles, links, runs without problems with my gcc.
> And, as far as I remember, it's legal, to compare pointers after
> conversion to long.[/color]
But the result is implementation defined. I know of at least one
system where it will fail to give the correct answer, then T is char.
For instance:
(long)(a + 7) > (long)(a + 8)
when a is an array of type char.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Comment