Reputation: 997
#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) .
Why is my code not correct ?
Upvotes: 1
Views: 737
Reputation: 134336
The syntax is correct when the []
is used as the postfix array subscription operator, not as an array declarator.
Quoting C11
, chapter §6.5.2.1
A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator [] is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
-th element ofE1
(counting from zero).
Upvotes: 6
Reputation: 409176
The expression a[i]
is equal to the expression *(a + i)
. Using the pointer-arithmetic syntax in declarations is invalid.
Upvotes: 11