영어로 읽는 코딩

29 [C] 포인터와 함수

Pointers and Function Arguments

Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function. For instance, a sorting routine might exchange two out-of-order elements with a function called swap. It is not enough to write

swap(a, b);

where the swap function is defined as

 

void swap(int x, int y)                  /* WRONG */

{

int temp;

 

temp = x;

x = y;

y = temp;

}

 

Because of call by value, swap can’t affect the arguments a and b in the routine that called it. The function above only swaps copies of a and b.

The way to obtain the desired effect is for the calling program to pass pointers to the values to be changed

swap(&a, &b);

Since the operator & produces the address of a variable, &a is a pointer to a. In swap itself, the parameters are declared to be pointers, and the operands are accessed indirectly through them.

 

void swap(int *px, int *py) /* interchange *px and *py */

{

int temp;

temp = *px;

*px = *py;

*px = temp;

}

Pictorially:

 

 

 

Pointer arguments enable a function to access and change objects in the function that called it.

 

[The C Programming Language p.95-96]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기