pass the pointer to the function
To pass a pointer to a function in the C programming language, you can declare a function parameter of type "pointer to a certain data type". Here's an example:
#include <stdio.h>
void changeValue(int *ptr) {
*ptr = 10;
}
int main() {
int num = 5;
printf("Before function call: %d\n", num);
changeValue(&num);
printf("After function call: %d\n", num);
return 0;
}
In this example, the changeValue
function takes a pointer to an integer (int ptr
) as a parameter. Inside the function, we dereference the pointer (ptr
) to access the value at the memory location it points to and assign it a new value (10
in this case).
In the main
function, we declare an integer variable num
and initialize it with 5
. We then call the changeValue
function, passing the address of num
(&num
) as an argument. This allows the function to modify the value of num
directly, even though it is defined in the main
function.
The output of this code will be:
Before function call: 5
After function call: 10
By passing a pointer to a function, you can modify variables in the calling function, even though they are outside the function's scope.