#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;
}
Look at the above code. It works perfectly.
However, after I changed p[row] into *(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;
}
it can't be compiled and displays the following error message :
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])
At my current level, I barely understand it.
In C, I thought a[i] = *(a + i) .
You can't pass parameters in a reference to a function.
ReplyDelete