Pointers Use Cases
When you pass a variable to a function, you're essentially passing its value. This means the function receives a copy of the data. Any modifications made inside the function do not affect the original variable.
main.cpp
99
1
2
3
4
5
6
7
8
9
10
#include <iostream>
void increment(int num) { num++; }
int main()
{
int num = 5;
increment(num);
std::cout << "Original value: " << num << std::endl;
}
12345678910#include <iostream> void increment(int num) { num++; } int main() { int num = 5; increment(num); std::cout << "Original value: " << num << std::endl; }
We can use pointers to enable a function to alter the original variable. This involves passing a memory address as an argument instead of the actual value.
main.cpp
99
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
void increment(int* num) { (*num)++; }
int main()
{
int num = 5;
int* p_num = #
increment(p_num);
std::cout << "Original value: " << num << std::endl;
}
123456789101112#include <iostream> void increment(int* num) { (*num)++; } int main() { int num = 5; int* p_num = # increment(p_num); std::cout << "Original value: " << num << std::endl; }
Note
You can bypass the creation of a pointer to a variable and instead directly use the address-of operator when passing a variable.
Uppgift
Swipe to start coding
- Create a function that swaps values of two variables.
- Call this function.
- Output the values of variables after the swap.
Lösning
solution.cpp
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
void swap(int* a, int* b)
{
int temporary = *a;
*a = *b;
*b = temporary;
}
int main()
{
int first = 100;
int second = 0;
swap(&first, &second);
std::cout << first << ' ' << second;
}
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 1. Kapitel 4
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
void swap(int _ p_first, int _ p_second)
{
int temporary = _ ___;
* ___ = _ ___;
_ ___ = temporary;
}
int main()
{
int first = 100;
int second = 0;
swap(___, ___);
std::cout << first << ' ' << second;
}
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal