Pointer's and thing's i don't understand about them

hey I am currently a "Beginner" in C++ and in general coding .
I have a question regarding Pointer's

#include <iostream>
#include <cmath>

using namespace std;

int main(){
int a1;
int * b1 , *a2;

a2 = &a1;
*b1 = a1;

cin >> a1;
cout << a1 << "\n" << a2 << "\n" << b1 << "\n" ;

system("pause");
return 1;
}

so here's what I don't get
in a2 = &a1 ; everything there is ok but how come i can't do *b1 = a1?
in my mind it's saying , value of b1 = a1 , so if i gave a1 the integer 31 why does it show a weird-ish equation in the result's
Last edited on
*b1 will dereference b1 and go to whatever address is stored in it. However, you never put an address into b1, so you cannot try to dereference it yet. You could create another integer and put its address into b1 just like you did with a2 = &a1.

Also, in your cout statement, if you just say cout << a2 it will print out the address stored in a2, not the value in that address. Not sure if this is what you're intending so I figured I'd point it out.
so basically your saying that in order to show *b1's value i have to give it a adress for the console to locate it from and find it's value?

and for the cout << a2, it's only printing the adress that it's given or is it printing out a2's actual adress?
Yes, if you don't give b1 an address yourself there will just be some random garbage in there, and attempting to dereference that will likely cause a problem.

cout << a2 will print the address that's stored in a2. If you wanted to print out the address of a2, you could do cout << &a2.
oh i get it now thanks,
after trying different combination's of code i stumbled upon something so simple i slapped my self... solution =

b1 = &a1;

cout << *b1 ;

thanks saved my brain from a melt down
Last edited on
No problem. Pointers were by far the hardest thing for me to understand when I first started. You can do a lot of cool things with them once you understand them though, so it's worth it.
I know you already helped me with my problem but im curious on to what Pointer's can do and how are they considered cool? because originally i was going to skip them because they where so confusing
Last edited on
At first pointers seem pretty useless and just confusing, but the deeper you go into c++ the more you will see how useful pointers are. The most common example of how pointers are useful is probably dynamic memory allocation. This, as the name suggests, allows you to allocate memory dynamically, as in while the program is running. You'll probably be introduced to this soon, as I was just a few days after first learning about pointers.
Topic archived. No new replies allowed.