Pointers and references
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Every variable has an address in memory. A pointer holds an address:
int hp = 100;
int *p = &hp; // & — take the address; p points to hp
*p = 50; // * — dereference: "what p points to"; now hp == 50
int *none = nullptr; // "points to nothing"
A reference is a second name for the same variable; it can't be "redirected" and it's never empty:
int &alias = hp; // alias and hp are the same cell
alias += 10; // hp == 60
What for: a function with a reference parameter, void heal(int &hp), changes the caller's variable, while without & it would get a copy.
A pointer to an array item can be moved: p + 1 is the next item (sizeof(int) bytes further on).
Task. Write a function void swapValues(int &a, int &b) that swaps the values, and a function
void minMax(const int *arr, int n, int *mn, int *mx) that returns the minimum and maximum through pointers.
Read a b, swap them and print them; then read n and n numbers and print the minimum and maximum.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.