Do these statements about pointers have the same effect?

后端 未结 4 1155
梦毁少年i
梦毁少年i 2020-11-27 05:59

Does this...

char* myString = \"hello\";

... have the same effect as this?

char actualString[] = \"hello\";
char* myString          


        
4条回答
  •  被撕碎了的回忆
    2020-11-27 06:02

    No.

    char  str1[] = "Hello world!"; //char-array on the stack; string can be changed
    char* str2   = "Hello world!"; //char-array in the data-segment; it's READ-ONLY
    

    The first example creates an array of size 13*sizeof(char) on the stack and copies the string "Hello world!" into it.
    The second example creates a char* on the stack and points it to a location in the data-segment of the executable, which contains the string "Hello world!". This second string is READ-ONLY.

    str1[1] = 'u'; //Valid
    str2[1] = 'u'; //Invalid - MAY crash program!
    

提交回复
热议问题