为什么不能使用'const int *'和'const char *'相同的方式创建int数组?

4 c++ arrays pointers literals

为什么我要以这种方式创建字符串或字符数组:

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

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

Sha*_*ger 5

“为什么”是:“因为字符串文字很特殊”。字符串文字存储在二进制文件中,作为程序本身的常量部分,并且const char *string = "Hello, World!";只是将文字视为存储在其他位置的匿名数组,然后将其存储在in中string

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

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

static const数组的作用是分配与字符串文字将使用的相同的恒定空间(尽管与字符串文字不同,编译器识别重复数组并合并存储的可能性较小),而是作为命名变量而不是匿名变量。可以通过相同的方式使字符串大小写明确:

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

但是直接使用文字会使事情更简洁。