Weird behavior of a pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mindhunter74
    New Member
    • Oct 2009
    • 7

    Weird behavior of a pointer

    The program below should outputs 'a' but it doesn't unless the commented line is uncommented.

    I use MinGW compiler.

    Code:
    int main()
    {
        char *cp;
        char a = 'a';
        char b = 'b';
        cp = &b;
        cp+=1;
        //printf("ap=%p\n",&a);
        printf("%c", *cp);
        return 0;
    }
  • faldahlawi
    New Member
    • Jul 2011
    • 1

    #2
    try changing line 7. with cp-=1; ... because you declare a before b, therefore b comes after a.

    Comment

    • Mindhunter74
      New Member
      • Oct 2009
      • 7

      #3
      @Faldahlawi
      This is not true actually.
      Although a is defined before b in the code, b has a lower address than a. It should be cp+=1 because cp is initially set to &b.

      Note: If I changed cp to be initially set to a and changed the operation to cp-=1 , I still have the same weird behavior that the output is not correct (b) unless I print &b somewhere in the code.

      Comment

      • alexis4
        New Member
        • Dec 2009
        • 113

        #4
        In general it is bad programming to assume where a variable will "seat" and read it with a pointer. Put these variables in an array or struct to organize your memory and then read with the pointer.

        Comment

        • Ferdinend
          New Member
          • Jul 2010
          • 7

          #5
          This is because &a and &b are not consecutive. (Unless you store it in an array.) Still if you want to proceed, get the difference of address by x = &a-&b. Then do cp+=x. It will work.
          But it is not good programing practice. Use array concept.

          Comment

          • Banfa
            Recognized Expert Expert
            • Feb 2006
            • 9067

            #6
            As alexis4 says under no circumstances should you assume anything about the location of a variable that has not be obtained directly using the address of (&) operator and the rules given in the C/C++ standards.

            How the compiler/linker organises memory is completely platform dependent, the standard does not even mandate the heap and stack that most programmers talk of when memory operations rear their ugly head. The platform is free to do anything it wants in this respect.

            If you do this at best you will produce non-portable code that will be hard to maintain and at worst you will introduce undefined behaviour which will of course work fine up until the point it becomes critical and then fail i.e. it will work during testing and fail in front of the customer.

            Comment

            Working...