What is the difference between char array and char pointer in C?

diesel picture diesel · Apr 17, 2012 · Viewed 366.2k times · Source

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);
}

Answer

Jon picture Jon · Apr 17, 2012

char* and char[] 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 type char[] is provided where one of type char* is expected, the compiler automatically converts the array into a pointer to its first element.

Your example function printSomething expects a pointer, so if you try to pass an array to it like this:

char s[10] = "hello";
printSomething(s);

The compiler pretends that you wrote this:

char s[10] = "hello";
printSomething(&s[0]);