Advertisement
Caminhoneiro

Understenting Pointers

Apr 20th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include "stdafx.h"
  2. //Demo pointers
  3.  
  4.  
  5. #include <iostream>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. int main() {
  11.     int* pAPointer; //Declare pointer
  12.  
  13.     int* pScore; //Declare and initialize pointer
  14.  
  15.     int score = 1000;
  16.  
  17.     pScore = &score; //assign pointer pScore address of variable score
  18.  
  19.     cout << "Assigning &score to pScore\n";
  20.     cout << "&score is: " << &score << "\n";    //Address of score variable
  21.     cout << "pScore is: " << pScore << "\n"; //Address stored in pointer
  22.  
  23.     cout << "score is: " << score << "\n";
  24.     cout << "*pScore is: " << *pScore << "\n\n"; //value pointed to by pointer
  25.  
  26.     cout << "****Adding 500 to score****\n";
  27.     score += 500;
  28.     cout << "score is: " << score << "\n";
  29.     cout << "*pScore is: " << *pScore << "\n\n";
  30.  
  31.     cout << "****Assigning &newScore to pScore****\n";
  32.     int newScore = 5000;
  33.     pScore = &newScore;
  34.     cout << "&newScore is: " << &newScore << "\n";
  35.     cout << "pScore is: " << pScore << "\n";
  36.     cout << "newScore is: " << newScore << "\n";
  37.     cout << "*pScore is: " << *pScore << "\n\n";
  38.  
  39.     cout << "****Assigning &str to pStr****\n";
  40.  
  41.     string str = "score";
  42.     string* pStr = &str; //Pointer to string object
  43.  
  44.     cout << "str is: " << str << "\n";
  45.     cout << "*pStr is: " << *pStr << "\n";
  46.     cout << "(*pStr).size() is: " << (*pStr).size() << "\n";
  47.     cout << "pStr->size() is: " << pStr->size() << "\n";
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement