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

后端 未结 8 703
醉话见心
醉话见心 2020-11-22 06:03

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

  • char *p = \"hello\"
    

    This is a char pointer

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 06:18

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

提交回复
热议问题