I am having a tough time understanding the type and use of the name of the array in C. It might seems a long post but please bear with me.
I understand that the following statement declares a
to be of type int []
i.e array of integers.
int a[30];
While a
also points the first element of array and things like *(a+2)
are valid. Thus, making a
look like a pointer to an integer. But actually the types int []
and int*
are different; while the former is an array type and later is a pointer to an integer.
Also a variable of type int []
gets converted into a variable of type int*
when passing it to functions; as in C
arrays are passed by reference (with the exception of the sizeof
operator).
Here comes the point which makes me dangle. Have a look at the following piece of code:
int main()
{
int (*p)[3];
int a[3] = { 5, 4, 6 };
p = &a;
printf("a:%d\t&a:%d\n",a,&a);
printf("%d",*(*p + 2));
}
OUTPUT:
a:2686720 &a:2686720
6
So, how does the above code work? I have two questions:
a
and&a
have the same values. Why?- What exactly does
int (*p)[3];
do? It declares a pointer to an array, I know this. But how is a pointer to an array different from the pointer to the first element of the array and name of the array?
Can anyone clarify things up? I am having a hell of a lot of confusions.
I know that I should use %p
as a placeholder instead of using %d
for printing the value of pointer variables. As using the integer placeholder might print truncated addresses. But I just want to keep things simple.