Difference between char* and char[]

前端 未结 7 1260
清歌不尽
清歌不尽 2020-11-27 03:32

I know this is a very basic question. I am confused as to why and how are the following different.

char str[] = \"Test\";
char *str = \"Test\";
7条回答
  •  一个人的身影
    2020-11-27 03:40

    char str[] = "Test";
    

    Is an array of chars, initialized with the contents from "Test", while

    char *str = "Test";
    

    is a pointer to the literal (const) string "Test".

    The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "Test", while the pointer simply refers to the contents of the string (which in this case is immutable).

提交回复
热议问题