I am trying to understand pointers in C but I am currently confused with the following:
-
char *p = "hello"This is a char pointer pointing at the character array, starting at h.
-
char p[] = "hello"This is an array that stores hello.
What is the difference when I pass both these variables into this function?
void printSomething(char *p)
{
printf("p: %s",p);
}
char*andchar[]are different types, but it’s not immediately apparent in all cases. This is because arrays decay into pointers, meaning that if an expression of typechar[]is provided where one of typechar*is expected, the compiler automatically converts the array into a pointer to its first element.Your example function
printSomethingexpects a pointer, so if you try to pass an array to it like this:The compiler pretends that you wrote this: