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

发布于 2024-12-12 04:33:08 字数 592 浏览 0 评论 0原文

我知道它们是不同的,我知道它们有何不同,我阅读了我能找到的所有关于 char* 与 char[] 的问题,

但所有这些答案都没有告诉我们什么时候应该被使用。

所以我的问题是:

你什么时候使用

const char *text = "text";

以及什么时候使用

const char text[] = "text";

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

举个例子,哪个更好:(

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

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

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

I know they are different, I know how they are different and I read all questions I could find regarding 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::string is also an option but I specifically want to know about char pointer/array)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

仅此而已 2024-12-19 04:33:08

两者明显不同,首先:

  1. 第一个创建一个指针。
  2. 第二个创建一个数组。

请继续阅读以获取更详细的说明:

数组版本:

char text[] = "text"; 

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


指针版本:

char *text  = "text"; 

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

事实上,C++03 不赞成使用不带 const 关键字的字符串文字。因此声明应该是:

const char*text = "text";

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


哪个版本更好?

取决于用途。

  • 如果不需要对字符串进行任何更改,请使用指针版本。
  • 如果您打算更改数据,请使用数组版本。

编辑:我刚刚注意到(在评论中)OP寻求以下之间的差异:

const char text[]const char* text

那么上述不同点仍然除有关修改字符串文字的内容外均适用。使用 const 限定符,数组 test 现在是一个包含 const char 类型元素的数组,这意味着它们无法修改。

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

Both are distinctly different, For a start:

  1. The First creates a pointer.
  2. The second creates an array.

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 NULL terminator. The array text is 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 sizeof operator can be used to determine its size.


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.

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

const char*text = "text";

Also,you need to use the strlen() function, and not sizeof to find size of the string since the sizeof operator will just give you the size of the pointer variable.


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:

const char text[] and const char* text

Well the above differing points still apply except the one regarding modifying the string literal. With the const qualifier the array test is now an array containing elements of the type const char which implies they cannot be modified.

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.

温馨耳语 2024-12-19 04:33:08

可能最大的区别是您不能将 sizeof 运算符与指针一起使用来获取 begin 指向的缓冲区的大小,这与 const char[] 版本相同您可以在数组变量上使用 sizeof 来获取数组的内存占用大小(以字节为单位)。因此,这实际上取决于您想要使用指针或缓冲区做什么,以及您想要如何使用它。

例如,做:

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

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

会给你非常不同的答案。

Probably the biggest difference is that you cannot use the sizeof operator with the pointer to get the size of the buffer begin pointed to, where-as with the const char[] version you can use sizeof on 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.

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.

南城旧梦 2024-12-19 04:33:08

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

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

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.

烟酒忠诚 2024-12-19 04:33:08

请注意:

我会将其设为static const char sz[] = "hello";。如此声明的一个好处是,通过写入只读内存来更改常量字符串会导致程序崩溃。如果没有static,放弃常量然后更改内容可能会被忽视。

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

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.

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

揽月 2024-12-19 04:33:08

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

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.

瑶笙 2024-12-19 04:33:08

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

如此接近,但没有雪茄更多数组乐趣

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

使用指针 const char* 有一些缺点:

  1. 额外的变量
  2. 指针是可写的
  3. 通过指针访问字符串的额外间接
  4. 需要 2 个内存负载

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

so close but no cigar and more array fun

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

Using a pointer const char* has as disadvantages:

  1. An additional variable
  2. pointer is writable
  3. an extra indirection
  4. accessing the string through the pointer require 2 memory-loads
长亭外,古道边 2024-12-19 04:33:08

只是提一个小问题,即表达式:

const char chararr[4] = {'t', 'e', 'x', 't'};

是用 4 个字符初始化数组的另一种方法。

Just to mention one minor point that the expression:

const char chararr[4] = {'t', 'e', 'x', 't'};

Is another way to initialize the array with exactly 4 char.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文