Pointers and Functions
When you pass a variable to a function in C, you can do so either by value or by reference. Passing by value means the function receives a copy of the variable, so changes inside the function don't affect the original.
void update(int *p) {
*p = 100;
}
Passing by reference means sending the variable's address using a pointer. This allows the function to directly modify the original variable’s value.
main.c
12345678910111213141516#include <stdio.h> // Function that modifies the value of an integer using a pointer void setToTen(int *numPtr) { *numPtr = 10; // Dereference pointer and assign new value } int main() { int value = 5; printf("Before: %d\n", value); setToTen(&value); // Pass address of value to function printf("After: %d\n", value); return 0; }
In this example, the function setToTen takes a pointer to an integer as its parameter. Inside the function, the pointer is dereferenced using the * operator, allowing direct access to the memory location of the original variable. By assigning *numPtr = 10;, you update the value stored at that address. In main, the address of value is passed to setToTen using the & operator. As a result, after the function call, the variable value is changed from 5 to 10. This demonstrates how passing a pointer enables a function to modify the original variable, rather than just a local copy.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Fantastico!
Completion tasso migliorato a 9.09
Pointers and Functions
Scorri per mostrare il menu
When you pass a variable to a function in C, you can do so either by value or by reference. Passing by value means the function receives a copy of the variable, so changes inside the function don't affect the original.
void update(int *p) {
*p = 100;
}
Passing by reference means sending the variable's address using a pointer. This allows the function to directly modify the original variable’s value.
main.c
12345678910111213141516#include <stdio.h> // Function that modifies the value of an integer using a pointer void setToTen(int *numPtr) { *numPtr = 10; // Dereference pointer and assign new value } int main() { int value = 5; printf("Before: %d\n", value); setToTen(&value); // Pass address of value to function printf("After: %d\n", value); return 0; }
In this example, the function setToTen takes a pointer to an integer as its parameter. Inside the function, the pointer is dereferenced using the * operator, allowing direct access to the memory location of the original variable. By assigning *numPtr = 10;, you update the value stored at that address. In main, the address of value is passed to setToTen using the & operator. As a result, after the function call, the variable value is changed from 5 to 10. This demonstrates how passing a pointer enables a function to modify the original variable, rather than just a local copy.
Grazie per i tuoi commenti!