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

后端 未结 8 663
醉话见心
醉话见心 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:25

    From APUE, Section 5.14 :

    char    good_template[] = "/tmp/dirXXXXXX"; /* right way */
    char    *bad_template = "/tmp/dirXXXXXX";   /* wrong way*/
    

    ... For the first template, the name is allocated on the stack, because we use an array variable. For the second name, however, we use a pointer. In this case, only the memory for the pointer itself resides on the stack; the compiler arranges for the string to be stored in the read-only segment of the executable. When the mkstemp function tries to modify the string, a segmentation fault occurs.

    The quoted text matches @Ciro Santilli 's explanation.

提交回复
热议问题