C++ 何时使用 const char * 何时使用 const char []

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7903551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:40:54  来源:igfitidea点击:

When to use const char * and when to use const char []

c++c

提问by rve

I know they are different, I know how they are different and I read all questions I could find regarding char*vs char[]

我知道他们是不同的,我知道他们有什么不同,我阅读了我能找到的关于char*vs 的所有问题char[]

But all those answers never tell when they should be used.

但是所有这些答案都没有告诉何时应该使用它们。

So my question is:

所以我的问题是:

When do you use

你什么时候用

const char *text = "text";

and when do you use

你什么时候使用

const char text[] = "text";

Is there any guideline or rule?

有什么指导方针或规则吗?

As an example, which one is better:

举个例子,哪个更好:

void withPointer()
{
    const char *sz = "hello";
    std::cout << sz << std::endl;
}

void withArray()
{
    const char sz[] = "hello";
    std::cout << sz << std::endl;
}

(I know std::stringis also an option but I specifically want to know about charpointer/array)

(我知道std::string也是一个选项,但我特别想了解char指针/数组)

回答by Alok Save

Both are distinctly different, For a start:

两者明显不同,首先:

  1. The First creates a pointer.
  2. The second creates an array.
  1. First 创建一个指针。
  2. 第二个创建一个数组。

Read on for more detailed explanation:

继续阅读以获取更详细的解释:

The Array version:

阵列版本:

char text[] = "text"; 

Creates an array that is large enough to hold the string literal "text", including its NULLterminator. The array textis initialized with the string literal "text".The array can be modified at a later time. Also, the array's size is known even at compile time, so sizeofoperator can be used to determine its size.

创建一个足够大的数组来保存字符串文字“text”,包括它的NULL终止符。该数组text使用字符串文字“text”进行初始化。该数组可以在以后修改。此外,即使在编译时,数组的大小也是已知的,因此sizeof可以使用运算符来确定其大小。



The pointer version:

指针版本:

char *text  = "text"; 

Creates a pointer to point to a string literal "text". This is faster than the array version, but string pointed by the pointer should not be changed, because it is located in an read only implementation defined memory. Modifying such an string literal results in Undefined Behavior.

创建一个指向字符串文字“text”的指针。这比数组版本快,但不应更改指针指向的字符串,因为它位于只读实现定义的内存中。修改这样的字符串文字会导致Undefined Behavior

In fact C++03 deprecates use of string literal without the constkeyword. So the declaration should be:

事实上,C++03 不赞成使用没有const关键字的字符串文字。所以声明应该是:

const char*text = "text";

Also,you need to use the strlen()function, and not sizeofto find size of the stringsince the sizeofoperator will just give you the size of the pointer variable.

此外,您需要使用该strlen()函数,而不是sizeof查找字符串的大小,因为sizeof运算符只会为您提供指针变量的大小。



Which version is better?

哪个版本更好?

Depends on the Usage.

取决于用法。

  • If you do not need to make any changes to the string, use the pointer version.
  • If you intend to change the data, use the array version.
  • 如果不需要对字符串进行任何更改,请使用指针版本。
  • 如果您打算更改数据,请使用阵列版本。


EDIT: It was just brought to my notice(in comments) that the OP seeks difference between:

编辑:我刚刚注意到(在评论中)OP 寻求以下区别:

const char text[]and const char* text

const char text[]const char* text

Well the above differing points still apply except the one regarding modifying the string literal. With the constqualifier the array testis now an array containing elements of the type const charwhich implies they cannot be modified.

好吧,除了关于修改字符串文字的一点之外,上述不同点仍然适用。使用const限定符,数组test现在是一个包含类型元素的数组,const char这意味着它们不能被修改。

Given that, I would choose the array version over the pointer version because the pointer can be(by mistake)easily reseated to another pointer and the string could be modified through that another pointer resulting in an UB.

鉴于此,我会选择数组版本而不是指针版本,因为指针可以(错误地)轻松地重新定位到另一个指针,并且可以通过另一个指针修改字符串,从而导致 UB。

回答by Jason

Probably the biggest difference is that you cannot use the sizeofoperator with the pointer to get the size of the buffer begin pointed to, where-as with the const char[]version you can use sizeofon the array variable to get the memory footprint size of the array in bytes. So it really depends on what you're wanting to-do with the pointer or buffer, and how you want to use it.

可能最大的区别是您不能使用sizeof带有指针的运算符来获取开始指向的缓冲区的大小,而与const char[]您可以sizeof在数组变量上使用的版本一样,以字节为单位获取数组的内存占用大小。所以这真的取决于你想用指针或缓冲区做什么,以及你想如何使用它。

For instance, doing:

例如,做:

void withPointer()
{
    const char *sz = "hello";
    std::cout << sizeof(sz) << std::endl;
}

void withArray()
{
    const char sz[] = "hello";
    std::cout << sizeof(sz) << std::endl;
}

will give you very different answers.

会给你截然不同的答案。

回答by tenfour

In general to answer these types of questions, use the one that's most explicit.

一般来说,要回答这些类型的问题,请使用最明确的问题

In this case, const char[]wins because it contains more detailed information about the data within -- namely, the size of the buffer.

在这种情况下,const char[]获胜是因为它包含有关其中数据的更多详细信息——即缓冲区的大小。

回答by tenfour

Just a note:

只是一个注意事项:

I'd make it static const char sz[] = "hello";. Declaring as such has the nice advantage of making changes to that constant string crash the program by writing to read-only memory. Without static, casting away constness and then changing the content may go unnoticed.

我会做到的static const char sz[] = "hello";。这样的声明有一个很好的优势,即通过写入只读内存来更改该常量字符串会使程序崩溃。如果没有static,丢弃常量然后更改内容可能会被忽视。

Also, the staticlets the array simply lie in the constant data section instead of being created on the stack and copied from the constant data sectioneach time the function is called.

此外,static让数组简单地位于常量数据部分,而不是在每次调用函数时在堆栈上创建并从常量数据部分复制。

回答by William Pursell

If you use an array, then the data is initialized at runtime. If you use the pointer, the run-time overhead is (probably) less because only the pointer needs to be initialized. (If the data is smaller than the size of a pointer, then the run-time initialization of the data is less than the initialization of the pointer.) So, if you have enough data that it matters and you care about the run-time cost of the initialization, you should use a pointer. You should almost never care about those details.

如果使用数组,则数据在运行时初始化。如果使用指针,运行时开销(可能)会更少,因为只需要初始化指针。(如果数据小于指针的大小,则数据的运行时初始化小于指针的初始化。)因此,如果您有足够重要的数据并且您关心运行时初始化的成本,你应该使用一个指针。你几乎不应该关心这些细节。

回答by mirk

I was helped a lot by Ulrich Drepper's blog-entries a couple of years ago:

几年前,Ulrich Drepper 的博客条目对我帮助很大:

so close but no cigarand more array fun

如此接近但没有雪茄更多的阵列乐趣

The gist of the blog is that const char[]should be preferred but only as global or static variable.

博客的要点是const char[]应该首选,但只能作为全局或静态变量。

Using a pointer const char*has as disadvantages:

使用指针const char*有以下缺点:

  1. An additional variable
  2. pointer is writable
  3. an extra indirection
  4. accessing the string through the pointer require 2 memory-loads
  1. 附加变量
  2. 指针可写
  3. 额外的间接
  4. 通过指针访问字符串需要 2 次内存加载