c++ - 为什么我不能使用与 'const int*' 相同的 'const char*' 创建一个 int 数组?

标签 c++ arrays pointers literals

为什么我可以用这种方式创建一个字符串或字符数组:

#include <iostream>
int main() {
  const char *string = "Hello, World!";
  std::cout << string[1] << std::endl;
}

?并且它正确输出第二个元素,而如果没有数组的下标符号 [ ] 我就不能创建整数类型的数组? char 的一个和这个有什么区别:const int* intArray={3,54,12,53};

最佳答案

“为什么”是:“因为字符串文字很特殊”。字符串文字存储在二进制文件中,作为程序本身的常量部分,const char *string = "Hello, World!"; 只是将文字视为存储在别处的匿名数组然后它存储一个指向 string 的指针。

对于其他类型没有等效的特殊行为,但是您可以通过创建一个命名的静态常量并使用它来初始化指针来获得相同的基本解决方案,例如

int main() {
  static const int intstatic[] = {3,54,12,53};
  const int *intptr = intstatic;
  std::cout << intptr[1] << std::endl;
}

static const 数组的作用是分配字符串文字将使用的相同常量空间(尽管与字符串文字不同,编译器不太可能识别重复数组并合并存储) ,但作为命名变量而不是匿名变量。字符串大小写可以用同样的方式显式显示:

int main() {
  static const char hellostatic[] = "Hello, World!";
  const char *string = hellostatic;
  std::cout << string[1] << std::endl;
}

但是直接使用字面量会让事情变得更简洁。

关于c++ - 为什么我不能使用与 'const int*' 相同的 'const char*' 创建一个 int 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44960672/

相关文章:

c++ - 函数 : smallest positive integer

c++ - 生成 "unique"矩阵

javascript - 合并 Material-UI 中的主题配置设置

C++/Qt获取指向指针的指针的值

c++ - 动态内存分配和指针非字符数组类型

Visual Studio 中的 C++ 错误

c++ - 在 map 中存储特定范围内的值

c++ - 按特定顺序迭代数组元素

javascript - 为什么在此实例中使用 `concat` 而不是 `push`?

C++ 字符串和指针