My professor has asked us to create a program that uses a pointer and will print the value of the pointer and the address of the variable. I've written what I think will give the correct address but I don't know how to check it and make sure its giving me the correct address. Is the following program giving me the address of the value a in the pointer?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main(){
int a = 5; //Decaring a value for a
int *B; //Declaring the pointer
B = &a;
cout << a <<" is the value of the variable."<<endl;
cout << B <<" is the address of the variable.";
return 0;
}
Yes your code is correct. Unfortunately there is know way to know the address of a variable until space is set aside for variable.
Try running the code below and see what is printed out.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main(){
int a = 5; //Declaring a value for a
int *B; //Declaring the pointer
B = &a;
cout << a <<" is the value of the variable a."<<endl;
cout << &a << " is the address of a.\n\n";
cout << B <<" is the address of the variable.\n";
cout << *B <<" is the value of B.\n";
return 0;
}
This would be about the only way to check an address of a variable.
Thanks so much Andy for the help! I'm guessing what he wanted was a little more similar to yours. I believe when I put B = &a it is a little excessive. I just fixed it to be:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int main(){
int a = 5; //Decaring a value for a
cout << a <<" is the value of a.\n\n"<<endl;
cout << &a <<" is the address of a.";
return 0;
}
This is working, its giving me the value and an address of the value.
Glad it worked out for you. What I showed you is more than you need, but it helps explain what is happening. What you came up with works fine and is a shorter way of saying the same thing. Good work.
If yo are finished here put the green check on the subject to let everyone know you have found your answer.