【发布时间】:2019-03-21 20:10:15
【问题描述】:
#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;
}
看上面的代码。效果很好。
但是,在我把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;
}
无法编译并显示以下错误信息:
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])
以我目前的水平,我几乎看不懂。
在 C 中,我认为 a[i] = *(a + i) 。
为什么我的代码不正确?
【问题讨论】:
-
您混淆了 3 个不同的术语。数组变量声明不同于函数参数声明,函数参数声明不同于使用数组的表达式。
标签: c function pointers arguments