Doubt in program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sridhard2406
    New Member
    • Dec 2007
    • 52

    Doubt in program

    Hi All,
    First Wish you a happy new year.

    Please conform me, my understanding is correct on below program.

    #include <stdio.h>

    main()
    {
    int *p;

    printf("%d", ((int )(p+1) - (int )p));
    }



    If I remove cast operation (int ). compiler explicitly will give the difference between the int * pointer. ie. 1.

    If I use cast operator, compiler will update the difference of two integer..ie 4.

    Thanks in advance.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    I'm not sure about 'update' part of 'compiler will update the difference of two integer'. If we assume that int and pointer are 32 bit, then yes, most likely it will return differnce in byte addresses between this and next element pointer by p, i.e. 4. However "The format in which this integer value represents a pointer is platform-specific". It's not an exact quote from the standard, but it means that there may be a system (with 32 bit integer and pointer) where it will return something other than 4.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      When you subtract two pointers, the compiler subtracts the two addresses and then divides the answer by the sizeof the type. So the different between p+1 and p is 1 int.

      The pointers contain addresses. Not int values. That cast tells the compiler to treat the addresses as int values. What you see is the difference between the addresses in bytes. On a 32-bit system an int is usually 4 bytes.

      Comment

      • sridhard2406
        New Member
        • Dec 2007
        • 52

        #4
        Thanks for you reply

        Comment

        Working...