Issue with dereferencing pointers

Greetings,

I'm having an issue with dereferencing pointers:

main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include "pointer_class.h"

using namespace std;

void print(int a);

int main(){
	int b = 50;
	pointer_class b_c;
	b_c.create(b);
	print(b);
	b_c.print();
	b = 43;
	print(b);
	b_c.print();
	cin.get();
}

void print(int a){
	std::cout << "a = " << a << std::endl;
}
pointer_class.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

class pointer_class{
private:
	int * a_p;
public:
	void pointer_class::create(int a){
		a_p = &a;
	}
	void pointer_class::print(){
		std:: cout << "*a_p = " << *a_p << std::endl;
	}
};

Output:
a = 50
*a_p = 12260645
a = 43
*a_p = 12260672
What I am trying to do is print out the value of a by dereferencing a_p, which points to a. However, I am getting these unwanted results. (12260645 instead of 50 and 12260672 instead of 43.)

Any help would be appreciated!
Last edited on
closed account (z05DSL3A)
void pointer_class::create(int a){ a needs to be a reference [create(int & a)]

With your create() as it is, a copy of the int is made and the pointer is set to point at this copy.
Last edited on
Thank you for your fast response. I changed my code as you suggested and it works perfectly fine now.

I apologize if this question has been asked before, I didn't really know the right search terms :/
Topic archived. No new replies allowed.