const char []和const char *之间的区别 [英] Difference Between const char[] and const char*

查看:95
本文介绍了const char []和const char *之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以本文正在讨论声明诸如const char* foo = "foo"之类的字符串文字的用法.它以声明结尾:

So this article is discussing the use of declaring a string literal like const char* foo = "foo" it ends with the claim:

const char *foo = "foo";
几乎从来不是你想要的.而是,您要使用以下形式之一:

const char *foo = "foo";
is almost never what you want. Instead, you want to use one of the following forms:

  • 对于要导出的字符串:
    const char foo[] = "foo";
  • 对于要在同一源文件中使用的字符串:
    static const char foo[] = "foo";
  • 对于要在同一库的多个源文件中使用的字符串:
    __attribute__((visibility("hidden"))) const char foo[] = "foo";
  • For a string meant to be exported:
    const char foo[] = "foo";
  • For a string meant to be used in the same source file:
    static const char foo[] = "foo";
  • For a string meant to be used across several source files for the same library:
    __attribute__((visibility("hidden"))) const char foo[] = "foo";

我在这里的理解是const char* const foo = "foo"等同于const char foo[] = "foo"只是因为我们在谈论的C字符串指针永远不能更改为指向其他任何东西,而const char* foo = "foo"可以用于指向任何其他C字符串.

My understanding here is that const char* const foo = "foo" is equivalent to const char foo[] = "foo" simply because we're talking about a C-string pointer that can never be changed to point at anything else, whereas const char* foo = "foo" could be used to point at any other C-String.

这是一个准确的简介吗?总是使用const char* constconst char[]吗?

Is this an accurate synopsis? Always use either const char* const or const char[]?

推荐答案

托马斯·马修斯的回答都指出了const char*const char* const是指针,而const char[]是数组.

As Thomas Matthews' answer states both a const char* and a const char* const are pointers, and a const char[] is an array.

但是有道理此处使用指针存在3个问题:

But as justified here there are 3 problems with using pointers:

  1. 需要存储指针存储空间
  2. 指针所引起的间接作用是必需的
  3. 指针需要为数组或数组大小单独存储结束指针

最终在链接中被证明是正确的

Ultimately as justified in the link:

简单的答案是,在声明变量时,您应该首选const char[].

这篇关于const char []和const char *之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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