c++ - 为什么多维数组中的空字符串文字会衰减为空指针?

标签 c++ pointers g++ language-lawyer c-strings

我想定义一个多维 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/

相关文章:

c - 在 C 中访问和修改字符串 (char*) 数组时出现段错误

c - 更安全的重新分配方式

c++ - 使 : g++: Command not found

c++ - 无法在 OSX 上运行已编译的 C++ 可执行文件,可在 Debian 上运行

c++ - Make_Pair 标识符在一个函数中未找到但在另一个函数中找到

java - 在构造函数中初始化

pointers - 通过引用传递自定义 slice 类型

c++ - 编译时出现警告,但程序可以运行;该怎么办?

c++ - 访问特定数组位置/索引时出现段错误

c++ - 我应该如何在 typedef 中定义一组位数?