skip to content

C Notes 3: Passing Arguments with Pointers

2 min read

This page was translated by AI

C functions use two main ways to pass arguments: pass by value and pass by reference.

Pass by value

  • The function receives only a copy of the argument. Assigning to that copy does not affect the original argument.

  • By default, C function arguments are passed by value.

int change(int x) {
x = 100;
return 100;
}
int main() {
int a = 10;
printf("%d\n", a); // 输出 10
change(a);
printf("%d\n", a); // 输出 10
}

Pass by reference

  • A function can access the original argument directly and change its value.

  • You can use the & operator to pass a reference.

    void change(int *ptr) {
    *ptr = 100;
    }
    int main() {
    int a = 10;
    int *ptr = &a;
    printf("%d\n", a); // 输出 10
    change(ptr);
    printf("%d\n", a); // 输出 100
    }

Summary

  • Understanding how C functions receive arguments is important for understanding and writing C programs.
  • When you need to change the value of an original argument, you can pass it by reference.

Additional knowledge

  • A pointer variable is essentially a variable that stores a memory address.
  • When a function receives a pointer variable, it changes the value that the pointer points to rather than creating a copy.
  • Assigning to a pointer variable inside a function does not change the pointer variable itself.

Appendix:

Pass by value

Suppose you have a basket containing 10 apples and want to give it to a friend.

With pass by value, you copy the apples from the basket and give the copy to your friend.

Your friend receives 10 apples, but the number of apples in your own basket remains unchanged.

Pass by value in C

In C, function arguments are passed by value by default.

This means that when you pass a variable to a function, the function receives only a copy of that variable.

Pass by reference

If you want a function to change the value of an original argument, you need to pass it by reference.

With pass by reference, you give your friend the address of the basket.

Your friend can then access your basket directly and change the number of apples in it.