Punteros: &, *, y paso por puntero
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.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Complete void add_one(int *p) para que sume 1 al entero al que apunta p. Use *p. No escriba un main — el verificador proporciona uno.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Complete void swap(int *a, int *b) para que intercambie los dos enteros. Use una variable temporal. No escriba un main.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Complete void min_max(const int a[], int n, int *min_out, int *max_out). Recorra el arreglo, luego escriba el valor más pequeño a través de min_out y el más grande a través de max_out. Asumir que n >= 1. No escriba un main.
Haz clic en Ejecutar para ver la salida aquí.