Complementary task for topic: 6
M Nemeth · 2023-08-29 15:21:04.626219'
Pointers: Pass Variable by Address
Pointers: Pass Variable by Address
Create a C program that demonstrates passing a variable by address to a function and modifying its value inside the function.
Hint: Define a function increment that takes an integer pointer as a parameter.
Inside the function, increment the value pointed by the pointer by 1.
In the main function, define an integer variable num and initialize it with some value.
Print the value of num before calling the increment function.
Call the increment function, passing the address of the num variable.
Print the value of num after calling the increment function to observe the change.
Solution
#include
void increment(int* ptr) {
(*ptr)++; // Increment the value pointed by the pointer
}
int main() {
int num = 10;
printf("Before increment: %d\n", num);
increment(&num); // Pass the address of num to the increment function
printf("After increment: %d\n", num);
return 0;
}
Explanation
n this task, we define a increment function that takes an integer pointer ptr as a parameter. Inside the increment function, we use the dereferencing operator * to access the value pointed by the pointer, and then we increment it by 1. In the main function, we have an integer variable num with an initial value of 10. We print the value of num before calling the increment function using printf(). We call the increment function, passing the address of the num variable using the & operator. Inside the increment function, the value pointed by the pointer is incremented, so the value of num in the main function is also changed.