Difference between using character pointers and character arrays

前端 未结 9 1179
不思量自难忘°
不思量自难忘° 2020-11-29 03:45

Basic question.

char new_str[]=\"\";

char * newstr;

If I have to concatenate some data into it or use string functions like strcat/substr/

9条回答
  •  鱼传尺愫
    2020-11-29 04:11

    The type of the first is char[1], the second is char *. Different types.

    Allocate memory for the latter with malloc in C, or new in C++.

    char foo[] = "Bar";  // Allocates 4 bytes and fills them with
                         // 'B', 'a', 'r', '\0'.
    

    The size here is implied from the initializer string.

    The contents of foo are mutable. You can change foo[i] for example where i = 0..3.

    OTOH if you do:

    char *foo = "Bar";
    

    The compiler now allocates a static string "Bar" in readonly memory and cannot be modified.

    foo[i] = 'X';  // is now undefined.
    

提交回复
热议问题