Hello,
Say I pass a two dimensional array to a function and receive it in the function definition, as either int* a or int a[][colsize]. I'm surprised that inside the function I cannot access it using both pointers and the normal array notation immaterial of how it was received by the function definition. Surprised because arrays are basically designed using pointers(jumping above memory locations intelligently) and I would have expected both to work because a[i][j] is basically *(a+i*colsize+j). Let me give an example
1.Receiving the array in the function definition using the array notation and trying to access elements using pointers
Code:
#include <stdio.h>
int i = 0;
int j = 0;
int main(void)
{
int a[2][5] = {
{1,2,3,4,5},
{6,7,8,9,10},
};
print(a);
return 0;
}
int print(int a[][5])
{
for(i=0;i<2;i++)
{
for(j=0;j<5;j++)
{
//printf("%d ",a[i][j]); This obviously works, but the one below does not work
printf("%d ",*(a+i*5+j)); //Does not work
}
printf("\n");
}
}
Output
Gives me a warning : warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat] and random output when I run it.
2.Receiving the array in the function definition using the pointer notation and trying to access using elements array notation
Code:
#include <stdio.h>
int i = 0;
int j = 0;
int main(void)
{
int a[2][5] = {
{1,2,3,4,5},
{6,7,8,9,10},
};
print(a);
return 0;
}
int print(int* a)
{
for(i=0;i<2;i++)
{
for(j=0;j<5;j++)
{
//printf("%d ",*(a+i*5+j)); This works, but why doesn't the notation below work? Aren't they the same thing?
printf("%d ",a[i][j]); //Does not work
}
printf("\n");
}
}
Output
error: subscripted value is neither array nor pointer nor vector
Works for oned arrays
I'm surprised because the same experiment works for one dimensional arrays and I'm able to use the notations interchangeably. See example below, both of these work
3.Receiving the array in the function definition using the array notation and trying to access using elements pointer notation. This works.
Code:
#include <stdio.h>
int i = 0;
int main(void)
{
int a[] = {1,2,3,4,5};
print(a);
return 0;
}
int print(int a[])
{
for(i=0;i<10;i++)
printf("%d ",*(a+i)); //Works fine
}
4.Receiving the array in the function definition using the pointer notation and trying to access using elements array notation. This also works
Code:
#include <stdio.h>
int i = 0;
int main(void)
{
int a[] = {1,2,3,4,5};
print(a);
return 0;
}
int print(int* a)
{
for(i=0;i<10;i++)
printf("%d ",a[i]);//Works fine
}
Please advise as to why 1 and 2(above) don't work.
Thanks.
Bookmarks