我想定义一个多维 C 字符串数组,由几个字符串文字初始化。在 C 我会做以下事情:
#include <stdio.h>
const char *strArr[2][1] = { {"foo"}, {""}};
int main(void) {
printf("%p\t%p\n", strArr[0][0], strArr[1][0]);
return 0;
}
编译
gcc -std=c18 -pedantic test.c
并执行结果:$ ./a.out
0x55d95410f004 0x55d95410f008
正如我所料,
strArr[1][0]
中的空字符串文字衰减为有效指针。但是,当我在 中尝试相同的代码时C++ :
#include <cstdio>
const char *strArr[2][1] = { {"foo"}, {""}};
int main(void) {
printf("%p\t%p\n", strArr[0][0], strArr[1][0]);
return 0;
}
编译
g++ -std=c++17 -pedantic test.cpp
并执行结果:$ ./a.out
0x55c61494d004 (nil)
这里,
strArr[1][0]
中的空字符串文字衰减为空指针。 为什么在 C++ 中会发生这种情况? 在 C++17 标准中,我在 5.13.5 第 16 段看到以下内容:
Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (6.7).
这似乎表明作为普通字符串文字的空字符串文字应该具有静态存储持续时间。那么为什么空字符串文字会衰减为空指针呢?
最佳答案
这种行为是不正确的,在这种情况下是 中回归的结果。海合会 :https://gcc.gnu.org/PR90947
回归已修复 GCC 9.3 版 并且应该有希望让它回到受影响的早期版本。
关于c++ - 为什么多维数组中的空字符串文字会衰减为空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076583/