本文介绍了指针const char vs char数组vs std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有两行代码

  const char * s1 =test 
char s2 [] =test;

两行代码都有相同的行为,所以我看不出任何区别, c $ c> s1 over s2 ,反之亦然。除了s1和s2之外,还有使用 std :: string 的方法。我认为使用std :: string的方式是最优雅的。看着其他代码,我经常看到人们使用const char * char s [] 。因此,我的问题是,我应该什么时候使用 const char * s1 char s [] std :: string

解决方案
  const char * s1 =test; 
char s2 [] =test;

这两个不相同。 s1 是不可变的:它指向常量内存。修改字符串文字是未定义的行为。



是的,在C ++中,应该优先使用 std :: string p>

Here I've two lines of code

const char * s1 = "test";
char s2 [] = "test";

Both lines of code have the same behavior, so I cannot see any difference whether I should prefer s1 over s2 or vice-versa. In addition to s1 and s2, there is also the way of using std::string. I think the way of using std::string is the most elegant. While looking at other code, I often see that people either use const char * or char s []. Thus, my question is now, when should I use const char * s1 or char s [] or std::string? What are the differences and in which situations should I use which approach?

解决方案
const char * s1 = "test";
char s2 [] = "test";

These two aren't identical. s1 is immutable: it points to constant memory. Modifying string literals is undefined behaviour.

And yes, in C++ you should prefer std::string.

这篇关于指针const char vs char数组vs std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:52