If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, function parameters can be passed in two ways: by value and by reference. When a parameter is passed by value, a copy of the value is passed to the function. Any changes made to the parameter inside the function do not affect the original variable. When a parameter is passed by reference, a pointer to the memory location of the variable is passed to the function. Any changes made to the parameter inside the function affect the original variable.
Passing a parameter by reference can be achieved by using a pointer. A pointer variable is declared by placing an asterisk (*) before the variable name, followed by the type of the variable it points to. For example, the following declares a pointer variable p
that points to an integer variable:
Copy code
int* p;
When a pointer variable is passed as an argument to a function, the function receives the memory address of the variable, not a copy of its value.
Here is an example of passing an integer variable by reference using a pointer:
Copy code
#include <stdio.h>
void increment(int* p) {
(*p)++;
}
int main() {
int x = 10;
increment(&x);
printf("x = %d\n", x);
return 0;
}
In this example, the increment()
function takes a pointer to an integer as an argument, which allows it to directly modify the value of the integer variable x
in the main function.
It's also important to mention that arrays and strings are passed to functions as pointers by default in C, so when we pass an array or a string to a function, it receives a pointer to the first element of the array or string, and it can directly access the memory location of the array or string elements and make changes to it.
Comments: 0