Function altering structure not reliable

I'm learning how to use pointer-to-structure to alter the value of the structure but I'm experiencing some weird behavior.

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
#include <iostream>

using namespace std;

struct map {
	int x;
	int y;
};

map plot(map *);

int main()
{
	map foo;

	map res = plot(&foo);

	cout << res.x << endl << res.y;

	cin.get();

    return 0;
}

map plot(map *ptr)
{
	ptr->y = 5;
	ptr->x = 3;

	map result = { ptr->y, ptr->x };

	return result;
}

What happens here is that I set the Y value to 5 and the X value to 3. As you can see I initialize Y first, but use cout on X first. After using cout on X it shows me the Y value

OUTPUT:
5
3
Last edited on
At line 30, you're creating a new map object, setting the value of result.x to ptr->y, i.e 5, and the value of result.y to ptr->x, i.e 3.
Topic archived. No new replies allowed.