Is a[i] really the same as *(a + i) in C?

#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

Answers (2)

Sourav Ghosh
Sourav Ghosh

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 that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Upvotes: 6

Some programmer dude
Some programmer dude

Reputation: 409176

The expression a[i] is equal to the expression *(a + i). Using the pointer-arithmetic syntax in declarations is invalid.

Upvotes: 11

Related Questions