2

I tried to access a data member by a pointer, so I write this code:

#include <iostream>
#include <string>

using namespace std;

class test{
public:
    int * returnAdd();
    int getA();
    void setmember(int x);
private:
    int a;
};

int *test::returnAdd()
{
    return &a;
}

int test::getA()
{
    return a;
} 

void test::setmember(int x)
    {
        a = x;

        return;
    }

int main(void)
{
    test test1;

    int *a = test1.returnAdd();
    test1.setmember(12);
    *a++;
    cout << test1.getA() << endl;
    cout << *a << endl;

    return 0;
}

I expect that the value of data member (a) would become 13 but it doesn't happen. then I printed the value of *a, and I was garbage. I wonder why the value of the data member doesn't change, while a is pointing to its location?? and why *a contains garbage and not even a copy of the value of data member a???

Fatemeh Karimi
  • 914
  • 2
  • 16
  • 23
  • [Recommended read](http://stackoverflow.com/a/18484907/7571258). He explains pretty good what expression `*a++` (aswell as variants `*++a` and `++*a`) actually do. – zett42 Mar 04 '17 at 17:41

4 Answers4

4

As a result of operator precedence, The post increment operator ++ is executed before a is dereferenced. Hence the original expression a, returned by the post increment operator is dereferenced.

Meanwhile a is incremented to point to the next non-existent adjacent memory. The next time you dereference a will invoke Undefined Behavior.

You probably wanted:

(*a)++;

Demo

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • _Hence you moved a to the next non-existent adjacent memory, then dereferenced it. Which invoked Undefined Behavior._ ... is not correct. The effect of `*a++` is that the pointer `a` is first dereferenced and then incremented. This [Example](http://coliru.stacked-crooked.com/a/fd98eb9e73f3da42) prints "1" then "2". If your statement were correct, it would print "2" and then "2" again. See [this answer](http://stackoverflow.com/a/18484907/7571258) for a good explanation. – zett42 Mar 04 '17 at 18:07
2

*a++; doesn't mean:

  1. Dereference a
  2. Increment it (what is pointed at by a)

*a++; means:

  1. Dereference a
  2. Increment the pointer a

Use (*a)++; to increment what is pointed at.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

You are moving a pointer, then reading from it. Try (*a)++;

lukeg
  • 4,189
  • 3
  • 19
  • 40
-2

It is private so you want to get It

Try to write a member function that does that for you

void test::add_one(void)
{
++a;
}

Always look for the easy way Hope this helps

techno01
  • 21
  • 4