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?
This behavior is not correct, and in this case is the result of a regression in GCC: https://gcc.gnu.org/PR90947
The regression has been fixed for GCC version 9.3 and should hopefully make it back to the earlier versions affected as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With