Help with pointers

Hi everyone, i'm having some difficulty with the output of my pointers. I'm fairly new to this so I know the code is probably sloppy. I'm just messing around with pointers and seeing what I can do with them. The problem is that when I go to output them it's displaying them in the opposite order that I want them to and I cannot figure out why. I've tried everything I could think of so I could use some help there is obviously something about them that I do not understand. Any other advice you can give me is much appreciated. thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 #include <iostream>
#include <string>
#include <sstream>
#include <ctype.h>

using namespace std;

void choice()
{
    cout << "\n\n[A]dd | [S]ubtract | [M]ultiply | [D]ivide\n";
}
double add(double a, double b)
{
    double c;
    c=a+b;
    return(c);
}
int main ()
{
    int a, b(0), c, d;

    char e;

    string s1;

    double a1[20];

    double * p1;

    cout << "Welcome to Calculator V.4 with pointers";
    cout << "\nPlease enter your number: \n";

    p1=a1;
    for(a=0 ; a<2 ; p1++ , a++)
    {
        cin >> *p1;
    }

    p1=&a1[b];

    cout << "\nWhat would you like to do with: " << *p1 << ", " << *p1++ ;

    return 0;
}
So by changing
 
 cout << "\nWhat would you like to do with: " << *p1 << ", " << *p1++ ;


to

 
 cout << "\nWhat would you like to do with: " << *p1 << ", " << *(p1+1) ;


I got it to work fine but I would still like to understand why the first option displayed them backwards
In your case, it is not *p1 which gets evaluated first, but *p1++.

1
2
3
4
5
6
7
8
x++;
// post-increment:
// returns the old value of x while having the side-effect
// that x is increased by next time it's looked at

++x;
// pre-increment:
// increases x and returns its new value, no side-effect 


So your post-increment operation *p1++ gets evaluated first.
p1++ returns the old p1 which points to the first element, with the side-effect mentioned above.

By when *p1 is evaluated it will have the new value from the side-effect.

You cannot rely on this behavior, it's undefined (UB - Undefined Behavior).
For other people it might print correctly.

Edit: actually it might not... because post-increment will return old value, so instead of reversing the numbers it would print the first number twice.
Last edited on
Oh ok I didn't think about that. Thanks these pointers have proven a difficult concept for me to get a grasp on haha, I started with them a few hours ago I just figured that I wasn't understanding something about them.
Just for fun. Let me know what it prints for you.

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::cout << (s += "Foo") << (s += "Bar") << std::endl;
}
BarFooBarFoo

It printed the same thing yours did
Topic archived. No new replies allowed.