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

  • A+
Category:Languages
#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 ?

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: