Incrementing pointer not working

前端 未结 5 1888
后悔当初
后悔当初 2021-01-24 02:30

I’m trying to increment pointer. I was sure that it is similar to do i+=1 , but I’m getting adress.

#include \"stdafx.h\" 
#include          


        
相关标签:
5条回答
  • 2021-01-24 02:50

    If you want your output to be "43", than you have to change *a++; to (*a)++;.

    But other than for testing and learning, code like yours is more of a "C thing" than a "C++ thing". C++ offers another approach to referencing data and operating on it, through what the language calls “references”.

    int i=42;
    int &a=i;  // ‘a’ is a reference to ‘i’
    a++;
    assert(i==43);  // Assertion will not fail
    

    References are especially useful for passing arguments to functions, without the risk of having null or displaced pointers.

    0 讨论(0)
  • 2021-01-24 02:54

    ++ has a higher operator precedence than the pointer dereference operator *.

    So what *a++ does is to return the value of i (the old value of *a) before incrementing the pointer value.

    After that expression has been evaluated, a now points to something other than the address of i, and the behaviour of a subsequent *a is undefined.

    If you want to increment i via the pointer, then use (*a)++;

    0 讨论(0)
  • 2021-01-24 02:56

    What does "I'm getting adress" mean?

    Have you checked out order of operations?

    http://en.cppreference.com/w/cpp/language/operator_precedence

    ++-postfix is a higher precedence than *-dereference - hence:

    *a++;
    

    is really:

    *(a++);
    

    and not:

    (*a)++;
    

    ... as you probably meant. Which is IMHO why I always recommend erring on the side of too many parentheses rather than too few. Be explicit as to what you mean :)

    0 讨论(0)
  • Your code works fine till you reach the line

    *a++;
    

    As you know, C++ compiler will break this code of line as

    *a = *(a+1);
    

    That is, it will first increment address value of a and then assign the value to *a. But if you do,

    *(a)++;
    

    then you will get correct output, that is, 43.

    For output- http://ideone.com/QFBjTZ

    0 讨论(0)
  • 2021-01-24 03:03

    You have used *a++;

    As your increment operator ++ has higher precedence than your pointer *, what actually is happening is that your pointer address is being incremented. So the new *a has no defined value and hence it will give an undefined value *a++; is the equivalent of a++;

    To fix this you can use parentheses (*a)++; or simply us pre increment operator ++*a;

    0 讨论(0)
提交回复
热议问题