Указатели: &, *, и передача по указателю
A problem from last lesson
- In lesson 5, a function got a copy of your number. Changing the copy did not change the original.
- C copies every argument you pass to a function. So a normal function cannot change your variable.
- To change it, the function needs the variable's address — where it lives in memory.
Every variable has an address
- Think of a variable as a box in memory. The value is kept inside the box.
- Every box has an address: a number that says where the box is.
- The
&operator gives you that address.&xmeans "the address ofx".
A pointer holds an address
- A pointer is a variable that stores an address, not a normal value.
- You declare one with a
*:int *p = &x;reads as "ppoints tox". - To reach the value at that address, put
*in front:*p. This is called dereference. - Changing
*pchanges the original variable.*p = 5;puts5intoxitself.
#include <stdio.h>
void set_to_five(int *p) {
*p = 5; // change the value at the address
}
int main(void) {
int x = 0;
set_to_five(&x); // pass the ADDRESS of x
printf("%d\n", x); // 5 — the original changed!
return 0;
}
Out-pointers: giving back more than one answer
- A function can
returnonly one value. But it can change several variables through pointers. - You pass the address of each answer, like
find(&min, &max). The function writes into them with*. - These extra pointer parameters are called out-pointers. The caller reads the answers after the call.
- A pointer that points to nothing is
NULL. Never dereference aNULLpointer.
Common mistakes
&xis the address ofx;*pis the value stored atp.- Never use
*pon an uninitialised orNULLpointer.
Now you try
- Each task gives you a function to complete. Use
*to read or change the value the pointer points to. - When a value comes in through a pointer (like
int *p), write your answer through it — do notreturnit. - Do not write a
main— the checker provides one. Use Check answer to compile your code with the supplied tests and view the results.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Завершите void add_one(int *p) так, чтобы она прибавляла 1 к int, на который указывает p. Используйте *p. Не пишите main — чекер предоставляет его сам.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Завершите void swap(int *a, int *b) так, чтобы она меняла местами два int. Используйте временную переменную. Не пишите main.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Завершите void min_max(const int a[], int n, int *min_out, int *max_out). Отсканируйте массив, затем запишите наименьшее значение через min_out и наибольшее через max_out. Предположите, что n >= 1. Не пишите main.
Нажмите Запустить, чтобы увидеть результат здесь.