为什么这个二维指针符号的作品和其他没有 [英] why this 2d pointer notation works and the other doesn't
问题描述
在这里,我已经写了一个code打印出3x3的matrix.Here我不得不矩阵传递给函数.The矩阵传递给指针数组的对角线值之和。code工作,但问题是我必须写在下面的方式参数
INT(*垫)[3]
以下会导致程序崩溃
为int *垫[3]
我想知道什么是两者之间的区别?为什么第二个导致程序崩溃?
全部code:
#包括LT&;&stdio.h中GT;诠释主(){ INT垫[3] [3];
INT I,J;
对于(I = 0; I&下; 3;我++){
为(J = 0; J&下; 3; J ++){
的printf(输入行%d栏%D =,I + 1,J + 1);
scanf函数(%d个,&安培;垫[I] [J]);
的printf(\\ n);
} }
//任务1:对角线值之和显示
diagonal_sum(垫);}diagonal_sum(中间体(*垫)[3]){//指针二维数组 的printf(\\ n角和\\ n);
INT总和= 0;
INT I;
对于(I = 0; I&下; 3;我++){
总和+ = *(*(垫+ I)+ I); //访问矩阵的对角线值
} 的printf(\\ ndiagonal总和=%d个\\ N,总和);
}
如果你正在写
INT(*垫)[3]
这意味着垫
是一个指向数组3 INT
秒。
在对方手中,
为int *垫[3]
手段,垫
是一个数组3 为int *
S(指针为整数)。
显然这两个是不同的类型。所以,你的指针运算出错。
现在,你可以理解,您的意见, //指向一个二维数组
,是不正确的。
Here i have written a code to print out the sum of diagonal values of a 3x3 matrix.Here I have to pass the matrix to a function .The matrix is passed to an array of pointers.Code works but the problem is I have to write the parameter in the following manner
int (*mat)[3]
the following causes the program to crash
int *mat[3]
I would like to know what is the difference between the two? and why the second one causes the program to crash ?
Full Code :
#include<stdio.h>
int main(){
int mat[3][3];
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("input row %d column %d = ",i+1,j+1);
scanf("%d",&mat[i][j]);
printf("\n");
}
}
// task 1 : Display sum of diagonal values
diagonal_sum(mat);
}
diagonal_sum(int (*mat)[3]){ // pointer to a 2d array
printf("\n DIAGONAL SUM \n");
int sum=0;
int i;
for(i=0;i<3;i++){
sum+=*(*(mat+i)+i); // access the diagonal values of the matrix
}
printf("\ndiagonal sum is = %d \n",sum);
}
In case you're writing
int (*mat)[3]
it means mat
is a pointer to an array of 3 int
s.
On the other hands,
int *mat[3]
means, mat
is an array of 3 int *
s (pointer to integers).
Clearly these two are different types. So, your pointer arithmetic goes wrong.
Now, you can understand, your comments, // pointer to a 2d array
, is not correct.
这篇关于为什么这个二维指针符号的作品和其他没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!