我刚刚遇到这个处理多维数组的程序。虽然我已经了解了它的要点,但有一个特殊的符号我不确定。
这个想法是将指针传递给多维数组的列,因为 2-Dim 数组不需要您提及 2D 矩阵中的行数。因此,指向 2D 矩阵列的指针 pm 被传递为: int (*pm)[COLUMN]
这是完整的程序:
#include<stdio.h>
#include<stdlib.h>
const int ROW = 2;
const int COL=3;
void fill_array(int (*pm)[COL], int row);
void display_array(int m[][COL], int row);
int main(int argc, char const *argv[])
{
/* code */
int i,j;
int m[ROW][COL];
//CALL function to enter elements
fill_array(m,ROW);
//display
display_array(m,ROW);
return 0;
}
void fill_array(int (*pm)[COL], int row)
{
int i,j;
printf("Please fill the array's content: \n");
for(i=0;i<row;i++)
{
for(j=0;j<COL;j++)
{
printf("\n m[%d][%d]: ",i,j);
scanf("%d", &pm[i][j]);
}
}
}
void display_array(int m[][COL], int row)
{
int i,j;
printf("\n Array's contents: \n");
for(i=0;i<row;i++)
{
for(j=0;j<COL;j++)
{
printf("%d\t", m[i][j]);
}
printf("\n");
}
}
我不确定指向数组的指针的表示形式。我的意思是我不熟悉这种将指针附加到数组的表示法。有人可以解释一下吗?
非常感谢!
最佳答案
当数组按值传递给函数时,它会转换为指向其第一个元素的指针。根据 C 标准(6.3.2.1 左值、数组和函数指示符)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
如果你传递这个数组
int m[ROW][COL];
一个函数,它被转换为指向其第一个元素的指针,该元素又是一个 int[COL]
类型的数组。指向该数组的指针看起来像
int ( * )[COL]
如果取消引用该指针,您将获得 int[COL]
类型的一维数组
例如,如果您声明了一个指向一维数组的指针,例如
int ( *pm )[COL]
然后表达式
*pm
类型为int[COL]
表达式 *pm
等价于 pm[0]
由于 pm[0]
是一个数组,那么您可以应用下标运算符 a第二次pm[0][0]
,将得到二维数组的第一个int
类型的元素。
关于c - 指向数组的指针的表示是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26927563/