Advertisement
aprsc7

Pointer

Dec 12th, 2019
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. /*
  2.     1. Relationship between pointer and array
  3.     2. Pointer as function parameters in program
  4.     3. Pointer to structure
  5.  
  6. */
  7.  
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. void display(int *);
  12.  
  13. struct robotStruct
  14. {
  15.     string model;
  16.     int version;
  17. };
  18.  
  19. int main()
  20. {
  21.     // 1. Relationship between pointer and array
  22.  
  23.     int array[5] = {1,2,3,4,5};
  24.  
  25.     cout << "array: " << array << endl; // array without index is address, 0x0001
  26.     cout << "array[0]: " << array[0] << endl; // array with index is data, 1
  27.     cout << "array + 1: " << (array+1) << endl << endl;
  28.  
  29.     int *ptr_array = array; // same since array already in address form
  30.  
  31.     // array access
  32.     cout << "array[0]: " << array[0] << endl; // index array is data, 1
  33.     cout << "ptr_array[0]: " << ptr_array[0] << endl; // index pointer is data, 1
  34.     cout << "(array+1): " << (array+1) << endl; // array++ without index is adding 1 to address, 0x0001+1 = 0x0002
  35.     cout << "*(array+1): " << *(array+1) << endl << endl; // dereference array++ same array[0+1], 2
  36.  
  37.     // 2. function in pointer
  38.     display(ptr_array);
  39.  
  40.     // 3. pointer to structure
  41.     robotStruct robot0 = {"UAV",5};
  42.  
  43.     robotStruct *rPtr;
  44.     rPtr = &robot0;
  45.  
  46.     cout << "rPtr.model: " << rPtr -> model << endl; // UAV
  47.     cout << "(*rPtr).version: " << (*rPtr).version << endl; // 5
  48.  
  49. }
  50.  
  51. void display(int *ptrTemp)
  52. {
  53.     cout << "ptrTemp: " << ptrTemp << endl; // 0x0002
  54.     cout << "*ptrTemp: " << *ptrTemp << endl; // 1
  55.     cout << "*(ptrTemp+1): " << *(ptrTemp+1) << endl << endl; // 2
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement