C Function Pointers Guide

In C language, you can modify variables outside a function by passing them as pointers in the function parameters. Here are the specific steps:

  1. Define a function that takes a pointer to a variable that needs to be modified as a parameter.
  2. Modify the value of a variable using a pointer within a function.
  3. When calling a function, pass the address of the variable that needs to be modified as a parameter.

The sample code is as follows:

#include <stdio.h>

// 定义一个函数,通过指针修改变量的值
void modifyValue(int *ptr) {
    *ptr = 10; // 修改指针指向的变量的值为10
}

int main() {
    int num = 5;
    
    printf("Before calling function: %d\n", num);
    
    // 调用函数并传递变量的地址作为参数
    modifyValue(&num);
    
    printf("After calling function: %d\n", num); // 输出修改后的值
    
    return 0;
}

In the example above, the modifyValue function was called by passing the address of the variable num as a parameter. Within the function, the value of num was changed to 10 using a pointer. The final output result is 10.

Before calling function: 5
After calling function: 10
bannerAds