carrayspointers

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


I am trying to understand pointers in C but I am currently confused with the following:

What is the difference when I pass both these variables into this function?

void printSomething(char *p)
{
    printf("p: %s",p);
}

Solution

  • 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]);