What's wrong with the initialization of s2 in the code below?
#include <stdio.h>
int main()
{
char *s1 = "foo";
char *s2 = {'f', 'o', 'o', '\0'};
printf("%c\n", s1[1]);
printf("%c\n", s2[1]);
return 0;
}
I thought because I could initialize s1 the way I did above, the initialization of s2 should work fine as well.
But this code leads to compile-time warnings as well as run-time segmentation fault.
$ gcc foo.c
foo.c: In function ‘main’:
foo.c:6: warning: initialization makes pointer from integer without a cast
foo.c:6: warning: excess elements in scalar initializer
foo.c:6: warning: (near initialization for ‘s2’)
foo.c:6: warning: excess elements in scalar initializer
foo.c:6: warning: (near initialization for ‘s2’)
foo.c:6: warning: excess elements in scalar initializer
foo.c:6: warning: (near initialization for ‘s2’)
$ ./a.out
o
Segmentation fault (core dumped)