亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

将数组传递给 C 中的函数

将数组传递给 C 中的函数

在本教程中,您将通过示例学习将数组(一维和多维数组)传递给 C 编程中的函数。

在 C 编程中,您可以将整个数组传递给函数。在我们学习之前,让我们看看如何将数组的各个元素传递给函数。


传递单个数组元素

将数组元素传递给函数类似于将变量传递给函数。


示例 1:传递单个数组元素

#include <stdio.h>
void display(int age1, int age2) {
  printf("%d\n", age1);
  printf("%d\n", age2);
}

int main() {
  int ageArray[] = {2, 8, 4, 12};

  // pass second and third elements to display()
  display(ageArray[1], ageArray[2]); 
  return 0;
}

输出

8
4

在这里,我们将数组参数传递给 display() 就像我们将变量传递给函数一样。

// pass second and third elements to display()
display(ageArray[1], ageArray[2]);

我们可以在函数定义中看到这一点,其中函数参数是单个变量:

void display(int age1, int age2) {
  // code
}

示例 2:将数组传递给函数

// Program to calculate the sum of array elements by passing to a function 

#include <stdio.h>
float calculateSum(float num[]);

int main() {
  float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

  // num array is passed to calculateSum()
  result = calculateSum(num); 
  printf("Result = %.2f", result);
  return 0;
}

float calculateSum(float num[]) {
  float sum = 0.0;

  for (int i = 0; i < 6; ++i) {
    sum += num[i];
  }

  return sum;
}

输出

Result = 162.50

要将整个数组传递给函数,只需将数组的名称作为参数传递。

result = calculateSum(num);

但是,请注意 [] 的使用 在函数定义中。

float calculateSum(float num[]) {
... ..
}

这会通知编译器您正在将一维数组传递给函数。


将多维数组传递给函数

要将多维数组传递给函数,只需将数组的名称传递给函数(类似于一维数组)。

示例 3:传递二维数组

#include <stdio.h>
void displayNumbers(int num[2][2]);

int main() {
  int num[2][2];
  printf("Enter 4 numbers:\n");
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 2; ++j) {
      scanf("%d", &num[i][j]);
    }
  }

  // pass multi-dimensional array to a function
  displayNumbers(num);

  return 0;
}

void displayNumbers(int num[2][2]) {
  printf("Displaying:\n");
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 2; ++j) {
      printf("%d\n", num[i][j]);
    }
  }
}

输出

Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

注意参数 int num[2][2] 在函数原型和函数定义中:

// function prototype
void displayNumbers(int num[2][2]);

这表示该函数将二维数组作为参数。我们还可以将超过 2 维的数组作为函数参数传递。

传递二维数组时,不一定要指定数组的行数。但是,应始终指定列数。

例如,

void displayNumbers(int num[][2]) {
  // code
}

注意: 在 C 编程中,可以将数组传递给函数,但不能从函数返回数组。


C语言

  1. C# 数组
  2. C 数据类型
  3. Python pass 语句
  4. Python 函数参数
  5. Python 闭包
  6. C - 函数
  7. C - 位域
  8. C - 文件 I/O
  9. C - 变量参数
  10. C++中的多态性
  11. C# - 方法
  12. C# - 代表