Re: Pointers in C



Praveen said:

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.

Even if the pointer arithmetic were legal (which others have already
pointed out, so I won't belabour it here), the call to printf is not.
Whether the (undefined) result of your illegal pointer arithmetic is
reported correctly by printf is undefined, because you failed to
provide a valid function prototype within the current scope at the
point of call to a variable argument function.

Headers are not decorative. They matter. In future, if you call printf,
do this:

#include <stdio.h>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
.



Relevant Pages

  • Re: c interview
    ... undefined behaviour because printf is a varidac function. ... stdio.h before using printf and other headers as appropriate before ... Would make it a point that the size of int is assumption to be .... ...
    (comp.lang.c)
  • Re: I fixed it!!!! here is the final code.
    ... > interpim wrote: ... >> int main ... > You could move this above the printf(), ... Lose the headers. ...
    (comp.lang.c)
  • Re: Can somebody help...
    ... a number of unsafe constructs and non-standard extensions. ... That value is too large to portably store in an int. ... This results in undefined behavior because you lied to printf about what ...
    (comp.lang.cpp)
  • Re: Is this correct..??
    ... long int i; ... Almost everthing is defined in assembler. ... Easily defeated by compiler optimisations. ... printf and that the first assignment to i is never used and decides to ...
    (comp.lang.c)
  • Semaphores Block when they Shouldnt and Dont when they Should
    ... took the votes (encoded in the first character of the transmitted mes- ... int socketAccess; ... write(voteSocket, voteBuffer, 2); ... {printf("Couldn't make a socket.\n"); ...
    (comp.unix.programmer)