Reputation: 785
I am trying to edit a string after initialization using character literals, as follows:
int main() {
char str1[10] = "hello";
str1[0] = "b";
printf("%s\n", str1);
return 0;
}
The result is "dello" i.e. a "d" not a "b". Likewise the below just gives nonsense.
int main() {
char str1[10];
str1[0] = "h";
str1[1] = "e";
str1[2] = "l";
str1[3] = "l";
str1[4] = "o";
printf("%s\n", str1);
}
I found one StackOverflow post that mentioned that this should cause a segfault or an Access-Violation error, but it doesn't really explain why.
Upvotes: 0
Views: 99
Reputation: 42838
str1[0] = "b";
Here, "b"
is a string literal, not a character. Characters are enclosed in single quotes:
str1[0] = 'b';
If you had compiler warnings enabled you'd get something like:
warning: incompatible pointer to integer conversion assigning to 'char' from 'char [2]' [-Wint-conversion]
str1[0] = "b"; ^ ~~~
In your second code, your string is missing a terminating null-character, and so passing it to printf
invokes undefined behavior because printf
can't know where your string ends. To append the null-character at the end, just do:
str1[5] = '\0';
Upvotes: 12
Reputation: 106
In C, single quotes identify chars and double quotes create a string literal.
Try doing the following:
str1[0] = 'b'; //note the single quote
Upvotes: 3