whats the difference between C strings and C++ strings?

前端 未结 3 910
执笔经年
执笔经年 2020-12-24 14:31

whats the difference between C Strings and C++ strings. Specially while doing dynamic memory allocation

3条回答
  •  孤独总比滥情好
    2020-12-24 15:21

    I hardly know where to begin :-)

    In C, strings are just char arrays which, by convention, end with a NUL byte. In terms of dynamic memory management, you can simply malloc the space for them (including the extra byte). Memory management when modifying strings is your responsibility:

    char *s = strdup ("Hello");
    char *s2 = malloc (strlen (s) + 6);
    strcpy (s2, s);
    strcat (s2, ", Pax");
    free (s);
    s = s2;
    

    In C++, strings (std::string) are objects with all the associated automated memory management and control which makes them a lot safer and easier to use, especially for the novice. For dynamic allocation, use something like:

    std::string s = "Hello";
    s += ", Pax";
    

    I know which I'd prefer to use, the latter. You can (if you need one) always construct a C string out of a std::string by using the c_str() method.

提交回复
热议问题