Cprogramming 简明教程

Passing Pointers to Functions in C

pointer In C 是一个变量,其中存储有其他变量的地址。它充当对原始变量的引用。可以向函数传递指针,就像传递任何其他参数一样。

A pointer In C is a variable that stores the address of another variable. It acts as a reference to the original variable. A pointer can be passed to a function, just like any other argument is passed.

可以在 C 中通过两种方式调用函数:

A function in C can be called in two ways −

要通过引用调用函数,需要定义该函数以在调用函数中接收指向 variable 的指针。以下是用于通过引用调用函数的 syntax

To call a function by reference, you need to define it to receive the pointer to a variable in the calling function. Here is the syntax that you would use to call a function by reference −

type function_name(type *var1, type *var2, ...)

通过引用调用函数时,将传递实际参数变量的指针,而不是其值。

When a function is called by reference, the pointers of the actual argument variables are passed, instead of their values.

Advantages of Passing Pointers to Functions

向函数传递指针有两个 advantages

Passing a pointer to a function has two advantages

  1. It overcomes the limitation of pass by value. Changes to the value inside the called function are done directly at the address stored in the pointer. Hence, we can manipulate the variables in one scope from another.

  2. It also overcomes the limitation of a function that it can return only one expression. By passing pointers, the effect of processing of a function takes place directly at the address. Secondly, more than one values can be returned if we return a pointer of an array or struct variable.

在本章中,我们将了解如何:

In this chapter, we shall see how to −

  1. Pass pointers to int variables

  2. Pass pointers to array

  3. Pass pointer to structure

Example of Passing Pointers to Functions

让我们定义一个函数 add() ,该函数接收两个变量的引用。调用这样的函数时,我们将传递实际参数的地址。让我们从 main() function 内部通过引用调用 add() 函数。

Let us define a function add() that receives the references of two variables. When such a function is called, we pass the address of the actual argument. Let us call the add() function by reference from inside the main() function.

#include <stdio.h>

/* function declaration */
int add(int *, int *);

int main(){

   int a = 10, b = 20;
   int c = add(&a, &b);
   printf("Addition: %d", c);
}

int add(int *x, int *y){
   int z = *x + *y;

   return z;
}

Output

Addition: 30

Swap Values by Passing Pointers

向函数传递指针最常被引用的应用之一就是我们可以如何交换两个变量的值。

One of the most cited applications of passing a pointer to a function is how we can swap the values of two variables.

以下函数接收要交换其值的两变量的引用:

The following function receives the reference of two variables whose values are to be swapped −

/* function definition to swap the values */
int swap(int *x, int *y){
   int z;
   z = *x;    /* save the value at address x */
   *x = *y;   /* put y into x */
   *y = z;    /* put z into y */

   return 0;
}

Example

main() 函数有两个变量 ab ;其地址作为参数传递给 swap() 函数。

The main() function has two variables a and b; their addresses are passed as arguments to the swap() function.

#include <stdio.h>

int swap(int *x, int *y){
   int z;
   z = *x;
   *x = *y;
   *y = z;
}

int main (){

   /* local variable definition */
   int a = 10;
   int b = 20;
   printf("Before swap, value of a: %d\n", a);
   printf("Before swap, value of b: %d\n", b);

   /* calling a function to swap the values */
   swap(&a, &b);
   printf("After swap, value of a: %d\n", a);
   printf("After swap, value of b: %d\n", b);

   return 0;
}

执行此代码时,将生成以下输出 −

When you execute this code, it will produce the following output −

Before swap, value of a: 10
Before swap, value of b: 20
After swap, value of a: 20
After swap, value of b: 10

Passing an Array Pointer to a Function

在 C 编程中,数组的名称充当数组第一个元素的地址;换句话说,它变成了指向数组的指针。

In C programming, the name of an array acts the address of the first element of the array; in other words, it becomes a pointer to the array.

Example

在此示例中,我们在 main() 中声明了一个未初始化的数组,并将它的指针连同整数一起传递给一个函数。

In this example, we declare an uninitialized array in main() and pass its pointer to a function along with an integer.

在函数内部,该数组会被填入传递整数的平方、立方和平方根。该函数返回此数组的指针,使用该指针可以访问值并在 main() 函数中打印值。

Inside the function, the array is filled with the square, cube and square root of the passed integer. The function returns the pointer of this array, using which the values are accessed and printed in the main() function.

#include <stdio.h>
#include <math.h>

int arrfunction(int, float *);

int main(){

   int x = 100;
   float arr[3];

   arrfunction(x, arr);

   printf("Square of %d: %f\n", x, arr[0]);
   printf("Cube of %d: %f\n", x, arr[1]);
   printf("Square root of %d: %f\n", x, arr[2]);

   return 0;
}

int arrfunction(int x, float *arr){
   arr[0] = pow(x,2);
   arr[1] = pow(x, 3);
   arr[2] = pow(x, 0.5);
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Square of 100: 10000.000000
cube of 100: 1000000.000000
Square root of 100: 10.000000

Passing String Pointers to a Function

我们来看另一个示例,其中我们将字符串指针传递给一个函数。

Let us have a look at another example, where we will pass string pointers to a function.

Example

在这个程序中,两个 strings 被传递到 compare() 函数。C 中的字符串是一个字符数据类型的数组。我们使用 strlen() function 来查找字符串的长度。

In this program, two strings are passed to the compare() function. A string in C is an array of char data type. We use the strlen() function to find the length of the string.

#include <stdio.h>

int compare(char *, char *);

int main(){

   char str1[] = "BAT";
   char str2[] = "BALL";
   int ret = compare(str1, str2);

   return 0;
}

int compare (char *x, char *y){

   int val;

   if (strlen(x) > strlen(y)){
      printf("Length of Str1 is greater than or equal to the length of Str2");
   }
   else{
      printf("Length of Str1 is less than the length of Str2");
   }
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Length of Str1 is less than the length of Str2

Passing Struct Pointer to a Function

在 C 编程中,一个 structure 是一个异构数据类型,其中包含不同 data types 的元素。让我们看看如何将结构指针传递给一个函数。

In C programming, a structure is a heterogenous data type containing elements of different data types. Let’s see how we can pass a struct pointer to a function.

Example

在这个例子中,在 main() 中声明了一个结构变量 rectangle ,并将它的地址传递给一个名叫 area() 的用户定义函数。当被调用时,area() 函数能够用间接操作符“ ”来使用变量的元素。它计算结果并把它赋给 area 元素 r→area。

In this example, a struct variable rectangle is declared in main() and its address is passed to a user-defined function called area(). When called, the area() function is able to use the elements of the variable with the indirection operator "". It computes the result and assigns it to the area element r→area.

#include <stdio.h>
#include <string.h>

struct rectangle{
   float len, brd;
   double area;
};

int area(struct rectangle *);

int main(){

   struct rectangle s;
   printf("Input length and breadth of a rectangle");
   scanf("%f %f", &s.len, &s.brd);
   area(&s);

   return 0;

}

int area(struct rectangle *r){

   r->area = (double)(r->len*r->brd);
   printf("Length: %f \n Breadth: %f \n Area: %lf\n", r->len, r->brd, r->area);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Input length and breadth of a rectangle
10.5 20.5
Length: 10.500000
Breadth: 20.500000
Area: 215.250000

概念 passing a pointer to a function 的逻辑扩展导致传递一个 Union 指针,即 multi-dimensional array 的指针,传递 self-referential structure 的指针,等等,所有这些在诸如复杂数据结构、硬件控制编程等不同的应用领域都有重要的用途。

The logical extension of the concept of passing a pointer to a function leads to passing a Union pointer, i.e., the pointer of a multi-dimensional array, passing the pointer of a self-referential structure, etc., all these have important uses in different application areas such as complex data structures, hardware control programming, etc.