I want to define a multidimensional C-string array, initialized by several string literals. In C I would do the following:
#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;
}
Compiling with gcc -std=c18 -pedantic test.c
and executing results in:
$ ./a.out
0x55d95410f004 0x55d95410f008
As I expect, the empty string literal in strArr[1][0]
decays to a valid pointer.
However, when I try the same code in 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;
}
Compiling with g++ -std=c++17 -pedantic test.cpp
and executing results in:
$ ./a.out
0x55c61494d004 (nil)
Here, the empty string literal in strArr[1][0]
decays to a null pointer. Why does this happen in C++?
In the C++17 standard, I see the following in 5.13.5 paragraph 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).
This seems to indictate that an empty string literal, being an ordinary string literal, should have static storage duration. So why would an empty string literal decay to a null pointer?
std::array
? – Eudoxia[2][2]
array, so mybad deleted comments and answer. What's the point of a[2][1]
array anyway? – Ski[2][1]
for the sake of illustration, not for any practical reason: it's a forced example to illustrate the issue. – Aggravationg++ (Gentoo 9.2.0-r2 p3) 9.2.0
– Aggravation\0
appended. – Aggravation