定义一个3行3列的整型二维数组arr和一个整型指针变量p,让p指向数组arr,使用指针变量p输入数组arr各元素的值,并求主对角线上各元素之和。
#include<stdio.h>#define N 3typedef int Type;void Add(Type* p){int sum=0,i;for (i = 0; i < N; i++){if ((p + N * (i)+i)!= (p + (N - 1) + (N-1) * i)){sum += (*(p + N * (i)+i));sum += (*(p + (N - 1) + (N-1) * i));}if ((p + N * (i)+i) == (p + (N - 1) + (N - 1) * i)){sum += (*(p + 3 * (i)+i));}}printf("主对角线上各元素之和:%d", sum);}int main(){int i;Type arr[N][N] = {0};Type* p;p = arr[0];for (i = 0; i < N * N; i++){scanf_s("%d", (p + i));}for(i=0;i<N*N;i++){printf("%3d", *(p + i));if ((i+1) % N == 0)printf("\n");}Add(p);return 0;}