PART 1
I have 2 strings and they are defined in following ways-
char s1[] = "foo";
char *s2 = "foo";
When I try to change a character of these strings, say, the 2nd character -
char s1[1] = 'x';
char s2[1] = 'x';
the character in string s1
changes, but changing the character in string s2
gives me this error - Segmentation fault (core dumped)
.
Why is it so?
Why am I unable to change the character of the string which is defined in the other way?
PART 2
Strings (they are array of characters, right?) can be initialized using - char *s = "foo"
but why does compiler gives warnings when I try to initialize arrays of different type using the same thing like int *arr = {1, 2, 3}
?
foo.c: In function ‘main’:
foo.c:5:5: warning: initialization makes pointer from integer without a cast [enabled by default]
foo.c:5:5: warning: (near initialization for ‘foo’) [enabled by default]
foo.c:5:5: warning: excess elements in scalar initializer [enabled by default]
foo.c:5:5: warning: (near initialization for ‘foo’) [enabled by default]
foo.c:5:5: warning: excess elements in scalar initializer [enabled by default]
foo.c:5:5: warning: (near initialization for ‘foo’) [enabled by default]
NOTE: My compiler is GCC.