[英]Passing an 2d array into a function using a pointer to pointer variable in c
[英]passing 2d array in c using pointer to pointer by typecasting
我正在搜索将2d数组传递给c中的函数,而我遇到了上述站点。 我理解了传递2d数组的第一种和第二种方法,但是我对第3种方法感到困惑,特别是,它甚至如何以这种方式工作?
3) Using an array of pointers or double pointer
In this method also, we must typecast the 2D array when passing to function.
#include <stdio.h>
// Same as "void print(int **arr, int m, int n)"
void print(int *arr[], int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3;
int n = 3;
print((int **)arr, m, n);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9
`
上面的代码在代码块上工作正常。 当从main()调用print()时 ,我们将arr作为参数传递,将其类型转换为指针的指针,但是在函数print()中,它仅取消引用一次以打印值。 printf("%d ", *((arr+i*n) + j));
应该不是*((*arr+i*n) + j));
,我尝试编译此语句,它可以编译但无法执行。
2) Using a single pointer
In this method, we must typecast the 2D array when passing to function.
#include <stdio.h>
void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
print((int *)arr, m, n);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9
`
第二种方法和第三种方法仅在print()函数中传递的参数类型不同,而其余代码相同。 那么功能的工作实际上有什么区别?
通过2D数组的最简单方法
功能
void PrintArray(unsigned char mat[][4]){
int i, j;
printf("\n");
for(i = 0;i<4;i++){
for(j = 0;j<4;j++)
printf("%3x",mat[i][j]);
printf("\n");
}
printf("\n");
}
主要
int main(){
int i,j;
//static int c=175;
unsigned char state[4][4], key[4][4], expandedKey[176];
printf("enter the value to be decrypted");
for(i=0;i<4;i++)
for(j=0;j<4;j++)
scanf("%x",(unsigned int *)&state[j][i]);
PrintArray(state);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.