Yeah, but why use Pointers? (Explanation here)

Hello Everybody,

so what I always find confusing about pointers, is that everytime someone has tried to reexplain them to me, I feel like I’m getting the Information Backwards.

So if you think you understand what Poimters are, but don’t quite get why were even using them, check this out:

Let’s suppose you have 5 pointers, all pointing to the same memory address:
int MyData = 10;
int *p1 = MyData;
int *p2 = MyData;
int *p3 = MyData;
int *p4 = MyData;
int *p5 = MyData;

So if we read the data Value pointed to by all these pointers, they will all return the value “10”. So, let’s change it!
*p1 = 20;

Now if you read the data value pointed to by all of these pointers, they will all return the value “20”.

What we’re doing with pointers is refrencing data values stored in specific areas of memory.
You can do other stuff with pointers, but just knowing one case for why you might use them, helps me atleast understand their purpose.

Hope this helps and wasn’t actually more confusing.

1 Like

I am confused why does

int* p1 = 20;

change the value pointed to by the other pointers, p2, p3, p4, p5? What are their values and why? Also does int myData change as well?

I’ll try to explain, hoping to increase my understanding of pointers at the same time.
I think there’s an error in Christopher’s examples, but I’ll use his values.

// Declare normal variable with value 10
int MyData = 10;

// Declare 5 pointers that all point to the memory address of the MyData variable
int *p1 = &MyData;   // Declare a pointer to the address of MyData
int *p2 = &MyData;   // You have to use & in front of the variable
int *p3 = &MyData;   // you want to get the address from
int *p4 = &MyData;   // If you don't you will make the value of the pointer
int *p5 = &MyData;   // point to the address of the value of the variable
					 // Without the & the pointer would point to memory number 10
					 // And you really don't know what's there so can be bad

*p1 = 20; // Make the value of the address p1 points to be 20
		  // You have not changed the value of the pointers
		  // You have now changed the value of the MEMORY SPACE
		  // the pointers point to

// to print the values you do like this
std::cout << "MyData cointains the value: " << MyData << "\n";
std::cout << "p1 points to the adress " << p1 << " which contains the value " << *p1 << "\n";

See the attached zip-file for a short program that I hope can explain it to you by showing.
ConsoleApplication1.zip (945 Bytes)

The output of the program will look like this:

Each time you run the program you will see that the values of MyData and the address the pointers points to (*p1, *p2 etc) stays the same, but the value of the pointers (p1, p2 etc) changes as the variable MyData is saved at different locations each time you run the program.

Hope this makes things a little clearer.

Privacy & Terms