You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言函数实现二维数组加法的编译错误排查与解决

二维数组加法代码编译错误的原因与解决方法

错误原因

在C语言中,二维数组作为函数参数时,必须显式指定第二维的长度。你代码里的int array[][]属于不完整类型,编译器无法确定数组每行的元素个数,也就没法正确计算数组元素的内存偏移地址,因此触发"type of formal parameter 1 is incomplete"和"array type has incomplete element type 'int[]'"错误。

修复方案

因为主函数中定义的二维数组是int array1[10][10](第二维长度固定为10),所以只需要把所有函数参数里的int array[][]修改为int array[][10]即可。如果后续需要调整数组大小,可以用宏定义统一管理第二维长度,方便维护。

修复后的完整代码

#include <stdio.h>
// 用宏定义统一管理列数,后续修改更方便
#define COLUMNS 10

void getArray(int array[][COLUMNS], int n, int m) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      printf("Enter value for array[%d][%d]: ", i, j);
      scanf("%d", &array[i][j]);
    }
  }
}

void addArray(int array1[][COLUMNS], int array2[][COLUMNS], int result[][COLUMNS],
              int n, int m) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      result[i][j] = array1[i][j] + array2[i][j];
    }
  }
}

void displayArray(int array[][COLUMNS], int n, int m) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      printf("%d ", array[i][j]);
    }
    printf("\n");
  }
}

int main() {
  int array1[COLUMNS][COLUMNS], array2[COLUMNS][COLUMNS], result[COLUMNS][COLUMNS], n, m;
  printf("Enter num of rows and columns: ");
  scanf("%d %d", &n, &m);
  // 增加合法性检查,避免输入的行列数超过定义的数组大小
  if (n > COLUMNS || m > COLUMNS) {
    printf("Error: Rows or columns cannot exceed %d\n", COLUMNS);
    return 1;
  }
  printf("Enter the values for array1:\n");
  getArray(array1, n, m);
  printf("\nEnter the values for array2:\n");
  getArray(array2, n, m);
  addArray(array1, array2, result, n, m);
  printf("\nThe sum of the two arrays is:\n");
  displayArray(result, n, m);

  return 0;
}

额外优化说明

  • 新增宏COLUMNS统一管理数组的列数,后续需要调整数组大小只需修改宏定义即可,无需逐一修改函数参数。
  • 增加了输入合法性检查,防止用户输入的行列数超过预定义的数组大小导致数组越界。

内容的提问来源于stack exchange,提问作者Affan M N M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:45:35