C++ strings: [] vs. *

后端 未结 6 1203
走了就别回头了
走了就别回头了 2020-12-02 09:22

Been thinking, what\'s the difference between declaring a variable with [] or * ? The way I see it:

char *str = new char[100];
char str2[] = \"Hi world!\";
<         


        
6条回答
  •  死守一世寂寞
    2020-12-02 09:33

    Okay, I had left two negative comments. That's not really useful; I've removed them.

    • The following code initializes a char pointer, pointing to the start of a dynamically allocated memory portion (in the heap.)
    
    char *str = new char[100];
    

    This block can be freed using delete [].

    • The following code creates a char array in the stack, initialized to the value specified by a string literal.
    
    char [] str2 = "Hi world!";
    

    This array can be modified without problems, which is nice. So

    
    str2[0] = 'N';
    cout << str2;
    

    should print Ni world! to the standard output, making certain knights feel very uncomfortable.

    • The following code creates a char pointer in the stack, pointing to a string literal... The pointer can be reassigned without problems, but the pointed block cannot be modified (this is undefined behavior; it segfaults under Linux, for example.)
    
    char *str = "Hi all";
    str[0] = 'N'; // ERROR!
    
    • The following two declarations
    
    void upperCaseString(char *_str) {};
    void upperCaseString(char [] _str) {};
    

    look the same to me, and in your case (you want to uppercase a string in place) it really doesn't matters.

    However, all this begs the question: why are you using char * to express strings in C++?

提交回复
热议问题