什么C字符串和C ++字符串之间的区别? [英] whats the difference between C strings and C++ strings?

查看:197
本文介绍了什么C字符串和C ++字符串之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么C字符串和C ++字符串之间的区别。特别是在做动态内存分配

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

推荐答案

我几乎不知道从哪里开始: - )

I hardly know where to begin :-)

在C,字符串都只是字符阵列当中,按照惯例,在结尾加上一个NULL字节。在动态内存管理方面,你可以简单地的malloc 对它们的空间(包括额外的字节)。修改字符串时内存管理的的责任:

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;

在C ++中,字符串(的std :: string的)与所有相关的自动内存管理和控制,这使得他们很多更安全和更容易使用,尤其是对对象新手。对于动态分配,使用这样的:

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";

我知道的的preFER使用,后者。您可以(如果你需要一个)总是通过构造一个C字符串了的std ::字符串 c_str 方法。

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.

这篇关于什么C字符串和C ++字符串之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆