I have just started learning 2D arrays in C and I came across this code where a 2D array is directly pre-incremented like this ++array
.
I tried to print the matrix in 3 different places(After initializing, in function after increment, in main function after function call), but I can't understand how the pre-incrementation works.
I also noticed that a[1][1]++
is reflected in the original matrix(8 is incremented to 9) but nothing else.
#include <stdio.h>
void printmatrix(int[3][3]);
int function(int a[][3])
{
int i,j;
++a; //what does this do?
printf("In function...\n");
printmatrix(a);
a[1][1]++;
}
void printmatrix(int a[3][3])
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("\n");
}
int main()
{
int a[3][3]={1,2,3,4,5,6,7,8,9};
printf("Initially...\n");
printmatrix(a);
function(a);
printf("In main...\n");
printmatrix(a);
printf("a[2][1]-a[1][2]=%d",a[2][1]-a[1][2]);
return 0;
}
The output that I got is,
Initially...
1 2 3
4 5 6
7 8 9
In function...
4 5 6
7 8 9
32765 0 0
In main...
1 2 3
4 5 6
7 9 9
a[2][1]-a[1][2]=3
Also when I tried to pre-increment the array after declaring it in the main function I got the following error.
int a[3][3]={1,2,3,4,5,6,7,8,9};
a++;
main.c: In function ‘main’:
main.c:28:2: error: lvalue required as increment operand
a++;