Advertisement
Cinestra

Question 4 of Pointer Problems

Jan 19th, 2023
873
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int* maxwell(int* a, int* b) //Maxwell takes the pointers of both int A and B
  5. {
  6.     if (*a > *b) //If the dereferenced value of A is greater than the dereferenced value of B, return A
  7.         return a; //Returns the pointer to A
  8.     else
  9.         return b;
  10. }
  11.  
  12. void swap1(int* a, int* b)
  13. {
  14.     int* temp = a;
  15.     a = b;
  16.     b = temp; //This probably tries swapping the pointers of A and B. However after the function is finished executing, the A and B will revert back to their original states.
  17.     // This function needed to have a reference to actually change the pointers of A and B.
  18. }
  19.  
  20. void swap2(int* a, int* b)
  21. {
  22.     int temp = *a;
  23.     *a = *b;
  24.     *b = temp; //Swaps the actual values of A and B
  25. }
  26.  
  27. int main()
  28. {
  29.     int array[6] = { 5, 3, 4, 17, 22, 19 };
  30.  
  31.     int* ptr = maxwell(array, &array[2]); //Puts ptr equal to whichever value is larger: either the start of the array or the third element of the array. In this case, it's the first element
  32.     *ptr = -1; //Sets the value pointed at by ptr equal to -1
  33.     ptr += 2; //Moves the pointer to point from the first entry to the third entry
  34.     ptr[1] = 9; //Sets the value of the element to the right of the pointer (which is currently pointing to the third entry) equal to 9. So in short, it sets the fourth entry equal to 9.
  35.     *(array + 1) = 79; //array is the start of the array (the first element). So the dereferenced next value is the second element. And it sets that equal to 79.
  36.  
  37.     for (int i = 0; i < 6; i++)
  38.         cout << "X " << array[i] << endl;
  39.  
  40.     cout << &array[5] - ptr << endl; //The pointer is still at the third entry. So the address of the 6th entry minus the address of the thirds entry is 3.
  41.    
  42.     swap1(&array[0], &array[1]); //This tries swapping the pointers of array[0] and array[1]. However, this doesn't really work so this call actaully does nothing.
  43.  
  44.     for (int i = 0; i < 6; i++)
  45.         cout << "Y " << array[i] << endl;
  46.  
  47.     swap2(array, &array[2]); //This swaps the values of the first element with the value of the third element.
  48.  
  49.     for (int i = 0; i < 6; i++)
  50.         cout << array[i] << endl;
  51. }
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement