All lessonsOpen Open Open Open Open
8. Pointers
Pointers as function arguments
0 of 5 activities0%
Reading 1
Out-parameters via pointers
A function can take a pointer parameter and write through it: void set(int* p) { *p = 5; }.
Call it with set(&x). This is another way to let a function modify the caller’s data — related to references, but with explicit addresses.
Check for nullptr before dereferencing when a pointer might be empty.
void setFortyTwo(int* p) {
if (p != nullptr) {
*p = 42;
}
}
int main() {
int x = 0;
setFortyTwo(&x);
cout << x << endl;
return 0;
}Check 2
Call site
To pass variable x to void f(int* p), you write
Fill in 3
Empty pointer
Try it 4
setFortyTwo
Call it on another variable.
main.cpp
Loading editor…
Output will appear here.
Assignment 5
Write addOne
Write void addOne(int* p) that adds 1 to the int pointed to by p. In main, read n, call addOne(&n), print n.
main.cpp
Loading editor…