Incrementing pointer not working

ε祈祈猫儿з 提交于 2020-11-29 10:35:18

问题


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 <iostream>
using namespace std;
int main()
{
    int i = 42;
    int *a = &i;
    *a++;
    cout << *a;
    cin.get();
    return 0;
}

Can anybody explain why ?


回答1:


++ 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)++;




回答2:


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.




回答3:


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 :)




回答4:


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;




回答5:


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



来源:https://stackoverflow.com/questions/34512482/incrementing-pointer-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!