p[] is an array. *p is a pointer. However, int p[] is an incomplete type so I'll say:
int p[5];
is the type. An array is a data type of consecutive elements of a specific type. A pointer simply points to one instance of a specific type.
When you pass an array to a function expecting a pointer, the compiler does not complain because the array, when used simply with it's name, degenerates into a pointer to the first element in the array. So you are actually passing a pointer, and not an array.
Code:
int func(int *pointer)
{
printf ("%d", *pointer);
return;
}
int main()
{
int p[5];
func(p); //passing a pointer
func(&p[0]); // equivalent
return 0;
}
p in main has 5 elements. pointer in func doesn't have elements, because it's not an array. It's just a container to hold a variable that refers to an instance of a type. You could access the element in an array if the pointer was pointing to an array like this:
Code:
int func(int *pointer)
{
printf ("%d", pointer[1]);
return;
}
int main()
{
int p[5] = {12, 23, 34, 45, 56};
func(p); //passing a pointer
func(&p[0]); // equivalent
return 0;
}
A side effect of this behavior is that you can't pass a copy of the array to a function. It always passes a pointer.
Code:
int func(int *pointer)
{
pointer[1] = 456;
return;
}
int main()
{
int p[5] = {12, 23, 34, 45, 56};
printf ("%d", p[1]);
func(p); //passing a pointer
func(&p[0]); // equivalent
printf ("%d", p[1]);//print 456
return 0;
}
You can use brackets with pointers because the inventors of the language knew that referring to arrays was a very common use for pointers, and so they decided to include it in the language.
Pointers might not point to anything. Arrays always have some elements.
http://www.cprogramming.com/tutorial/lesson6.html
http://faq.cprogramming.com/cgi-bin/...&id=1043284351
http://faq.cprogramming.com/cgi-bin/...&id=1073086407