在 C 中访问二维数组中的元素
我正在编写一个程序,该程序将2D char
数组传递到用于打印函数中。但是,当我尝试访问2D数组中的元素以进行打印时,我不能。只有在传递数组时,我将打印循环和语句放在Main()函数中时不会发生此问题。
有人可以帮助解释吗?
void disp_array(char* array)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
printf("%c", array[i][j]);
}
printf("\n");
}
}
附件是我的代码:j
在printf
语句中以错误:
e0142:“表达式必须具有指针到对象类型,但具有类型 int“
I am writing a program that passes a 2D char
array into a function for printing. However, when I try to access elements in the 2D array for printing, I can't. This problem does not occur when I place the printing loops and statements in the main() function, only if the array is passed.
Can someone help explain?
void disp_array(char* array)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
printf("%c", array[i][j]);
}
printf("\n");
}
}
Attached is my code: the j
in the printf
statement is highlighted with an error:
E0142: "expression must have pointer-to-object type but it has type
int"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
函数声明错误。
由于参数的类型为
char *
,因此表达式array[i]
会生成char
类型的标量对象,该对象将提升为该类型int
由于整数提升,您可能无法在尝试执行array[i][j]
时应用下标运算符。所以编译器会发出错误消息声明
该函数应该这样
:具有数组类型
char[SIZE][SIZE]
的参数由编译器隐式调整为类型char ( * )[SIZE]< /code> ,即该函数不知道存在多少
char ( * )[SIZE]
类型的元素,因此您需要显式指定元素的数量。 。以及您需要传递的数组 数组中的行数例如,
如果数组包含字符串,则函数定义将如下所示
The function declaration is wrong.
As the parameter has the type
char *
then the expressionsarray[i]
yields a scalar object of the typechar
that is promoted to the typeint
due to the integer promotions to which you may not apply the subscript operator as you are trying to doarray[i][j]
. So the compiler issues the error messageThe function should be declared like
or like
The parameter having the array type
char[SIZE][SIZE]
is implicitly adjusted by the compiler to the typechar ( * )[SIZE]
. That is the function does not know how many elements of the typechar ( * )[SIZE]
exist. So you need to specify the number of elements explicitly. Try always to define a more general function.And along with the array you need to pass the number of rows in the array. For example
If the array contains strings then the function definition will look like