0

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.

Community
  • 1
  • 1
user1379351
  • 723
  • 1
  • 5
  • 18
  • 3
    `str1[0] = "b";` ==> `str1[0] = 'b';` – Weather Vane Dec 30 '16 at 20:48
  • 1
    "... using character literals..." - those aren't character literals; they're *string* literals. – WhozCraig Dec 30 '16 at 20:48
  • 2
    You MUST heed compiler warnings. Your code generates several in GCC without even turning on extra warnings. – Random Davis Dec 30 '16 at 20:49
  • 2
    Did you not get something like: *"warning C4047: '=': 'char' differs in levels of indirection from 'char [2]'"*? Please enable compiler warnings and consider them to be errors. – Weather Vane Dec 30 '16 at 20:50
  • In C, `'b'` means "the number 66" (assuming ASCII), which is what you wanted, as opposed to `"b"` which means "the address in memory of two bytes I want you to allocate and fill with the numbers 66 and 0". – Lee Daniel Crocker Dec 30 '16 at 22:10

2 Answers2

12
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';
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • 1
    you should also either initiallize str1 like this: `char str1[10] = {0};` or set `str1[5] = '\0';` – bruceg Dec 30 '16 at 20:53
  • 1
    Thanks very much! (My compiler said "assignment makes integer from pointer without a cast [-Wint-conversion]", which meant nothing to me) – user1379351 Dec 30 '16 at 21:07
3

In C, single quotes identify chars and double quotes create a string literal.

Try doing the following:

str1[0] = 'b'; //note the single quote
Pavel B
  • 106
  • 6