Re: Pointers in C
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 21 Feb 2007 01:34:36 -0800
"Raman" <ramanchalotra@xxxxxxxxx> writes:
On Feb 21, 11:18 am, Ian Collins <ian-n...@xxxxxxxxxxx> wrote:
Praveen wrote:Can Some onr tell why these are unrelated?
Hi,
I came across a program as follows
main()
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", p1-p2);
}
The output of the above program is 1.
Can some one explain me how it is 1.
Because that's what your compiler gives as the answer, subtracting two
unrelated pointers is undefined behaviour.
Because they point to distinct objects.
Here's what the standard says in the section on relational operators
(<, <=, >, >=) (C99 6.5.8p5):
When two pointers are compared, the result depends on the relative
locations in the address space of the objects pointed to. If two
pointers to object or incomplete types both point to the same
object, or both point one past the last element of the same array
object, they compare equal. If the objects pointed to are members
of the same aggregate object, pointers to structure members
declared later compare greater than pointers to members declared
earlier in the structure, and pointers to array elements with
larger subscript values compare greater than pointers to elements
of the same array with lower subscript values. All pointers to
members of the same union object compare equal. If the expression
P points to an element of an array object and the expression Q
points to the last element of the same array object, the pointer
expression Q+1 compares greater than P. In all other cases, the
behavior is undefined.
(A non-array object is treated as an array of one element.)
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- Pointers in C
- From: Praveen
- Re: Pointers in C
- From: Ian Collins
- Re: Pointers in C
- From: Raman
- Pointers in C
- Prev by Date: Re: When to use automatic variables and when to use malloc
- Next by Date: Re: confused about extern use
- Previous by thread: Re: Pointers in C
- Next by thread: Re: Pointers in C
- Index(es):
Relevant Pages
|