I have came across a piece of code making the following initialization:
static const uint8_t s[] = {"Some string"};
I would expect it to be interpreted as follows: The right side is matching an array of char pointers with single element which points to a string literal "Some string". While the left part is an array of uint8_t
. Then the behavior I would expect is that the first element of s
to receive some truncated value of the pointer to the string literal, thus causing unexpected behavior in the following code, assuming s
is a string.
I've made the following test code:
#include <stdint.h>
#include <stdio.h>
static const uint8_t s1[] = "String1";
static const uint8_t s2[] = { "String2" };
int main(void){
printf("%p, %p\n", s1, s2);
printf("%s, %s\n", s1, s2);
return 0;
}
For my surprise it seems that it is not happening. Not only the code will work correctly, but also the disassembly shows that both s1
and s2
are initialize as the corresponding strings in identical way.
Is this something gcc
specific? Is C syntax permitting taking the single string literal into {}
and still interpret it as a string literal?
Quoted from N1570(the final draft of C11), 6.7.9 Initialization(emphasis mine):
- An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
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