+ 1

Pointers code

what If in this code #include <iostream> using namespace std; int main() { int score = 5; int *scorePtr; scorePtr = &score; cout << scorePtr << endl; return 0; } i want to know the content then how to rewrite the code??

15th Apr 2017, 7:14 AM
Shreya Parmar
Shreya Parmar - avatar
2 Respuestas
+ 13
cout << *scorePtr << endl;
15th Apr 2017, 7:20 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
How to use pointers : 1) To create a pointer of a given type we should do : type * pointer(nullptr); for example : int *pointer(nullptr); (nullptr) is a constant used to make sure your pointer doesn't store the adress of a random variable in the memory of the computer in the computer memory the addresses begin at 1 and nullptr is like 0. 2) If you want to get the adress of a variable that already exists you shouls use : pointer = &variable; because & return the adress of a variable. But you can also create a variable using a pointer like this : pointer = new int(); is we supposed that the pointer is a int* pointer. But be aware, if you do this and only if you do this, when the program will end, only the pointer will be destroy because the variable wouldn't have beem declared. So the destructor of the variable you have created using the pointer won't be called. So when you won't use the variable pointed with the pointer you should do : delete pointer; so you delete manually the variable. 3) Then you can use the pointer as any variable, and to access or modify the value of variable which is pointed by the pointer you can do (*pointer) that return something like a reference, so you can edit the variable. If the variable is an object of a class, instead of using (*pointer).method(); you can do pointer->method(); So then i let you rewrite your code :-) NB: if you are interested by pointers, you should look closer at the smarts pointers of the std library that allow you to use pointer without any problem of memory fleak.
15th Apr 2017, 7:58 AM
Glozi30
Glozi30 - avatar