Sle*_*der 1 c pointers arguments function
#include <stdio.h>
int sum2d(int row, int col, int p[row][col]);
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("%d\n", sum2d(2, 3, a));
return 0;
}
int sum2d(int row, int col, int p[row][col])
{
int total = 0;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
total += (*(p + i))[j];
return total;
}
Run Code Online (Sandbox Code Playgroud)
看看上面的代码.它完美地运作.
但是,在我将p [row]改为*(p + row)后,
#include <stdio.h>
int sum2d(int row, int col, int (*(p + row))[col]);
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("%d\n", sum2d(2, 3, a));
return 0;
}
int sum2d(int row, int col, int (*(p + row))[col])
{
int total = 0;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
total += (*(p + i))[j];
return total;
}
Run Code Online (Sandbox Code Playgroud)
它无法编译并显示以下错误消息:
test.c:2:38: error: expected ‘)’ before ‘+’ token
int sum2d(int row, int col, int (*(p + row))[col]);
^
test.c: In function ‘main’:
test.c:7:2: warning: implicit declaration of function ‘sum2d’ [-Wimplicit-function-declaration]
printf("%d\n", sum2d(2, 3, a));
^
test.c: At top level:
test.c:12:38: error: expected ‘)’ before ‘+’ token
int sum2d(int row, int col, int (*(p + row))[col])
Run Code Online (Sandbox Code Playgroud)
在我目前的水平,我几乎不理解它.
在C中,我认为[i] = *(a + i).
为什么我的代码不正确?
Som*_*ude 11
的表达 a[i]等于表达 *(a + i).在声明中使用指针算术语法无效.
当[]用作后缀数组预订运算符时,语法是正确的,而不是数组声明符.
引用C11,第6.5.2.1章
后缀表达式后跟方括号中的表达式
[]是数组对象元素的下标名称.下标operator []的定义与之E1[E2]相同(*((E1)+(E2))).由于适用于二元+运算符的转换规则,ifE1是一个数组对象(等效地,指向数组对象的初始元素的指针)并且E2是一个整数,因此E1[E2]指定E2-th元素E1(从零开始计数).