示例
//Visual Studio中加上这句才可以使用scanf() //否则只能使用scanf_s() #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> #define ROWS 3 #define COLS 4 void sum_rows(int ar[][COLS], int rows); void sum_cols(int [][COLS], int);//省略形参名 int sum2d(int (*ar)[COLS], int rows);//指针表示法 //多维数组只能省略最左边括号的大小,如ar[][2][3] //ar[2][3] 第1个括号里的2会被编译器忽略 //编译器会将数组表示法转成指针表示法(因为处理指针效率更高) //argc: 参数个数 argv[]: 参数数组 int main(int argc, char *argv[]) { int junk[ROWS][COLS] = { {2, 4, 6, 8}, {3, 5, 7, 9}, {12,10,8, 6} }; sum_rows(junk, ROWS); sum_cols(junk, ROWS); printf("Sum of all elements = %d\n", sum2d(junk, ROWS)); system("pause"); return 0; } void sum_rows(int ar[][COLS], int rows) { int r; int c; int tot; for (r = 0; r < rows; r++) { tot = 0; for (c = 0; c < COLS; c++) tot += ar[r][c]; printf("row %d: sum = %d\n", r, tot); } } void sum_cols(int ar[][COLS], int rows) { int r; int c; int tot; for (c = 0; c < COLS; c++) { tot = 0; for (r = 0; r < rows; r++) tot += ar[r][c]; printf("col %d: sum = %d\n", c, tot); } } int sum2d(int ar[][COLS], int rows) { int r; int c; int tot = 0; for (r = 0; r < rows; r++) for (c = 0; c < COLS; c++) tot += ar[r][c]; return tot; }