-1

If we want to increment the null character '\0' by 60, given the string size is known beforehand, then we can do the following:

#include <stdio.h>

int main() {
    char str1[] = "Hello!"; 
    str1[6] += 60;

    printf("%s\n", str1);

    return 0;
}

The output we get is:

Hello!<

However, if we do not know the string size, then we can use strlen as such:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello!"; 
    str1[strlen(str1) + 1] += 60;

    printf("%s\n", str1);

    return 0;
}

However, this outputs:

Hello!

As you can see, it doesn't change it at all. What am I doing wrong in the second case? Also, I thought that array size is static and does not change in size, so how can it be in the second case that we've "added" a character.

Chronollo
  • 322
  • 1
  • 9

2 Answers2

1

str1[strlen(str1) + 1] is the character AFTER the null terminator. Just change to str1[strlen(str1)]

Think about it. strlen("") is 0.

Also remember that C indexes arrays from zero, so the last character in a string str is located at str[strlen(str) - 1]

However, remember that it's not a good idea to print a string where you have altered the null terminator. That will cause undefined behavior when printing them, so strictly speaking, you cannot really draw conclusions from your output. In this case, what I said above is a very, very likely explanation. But if you invoke UB, the program becomes unpredictable.

klutt
  • 30,332
  • 17
  • 55
  • 95
0

Array indexes start from zero so it should be:

str1[strlen(str1)] += 60;

But you need also to add the null character.

str1[strlen(str1) + 1] = 0;

But remember that str1 array has to have enough space. You cant access arrays outside their bounds.

So it cant be defined as in your example. It has to have (at least) 8 elements:

char str1[8] = "Hello!"; 
0___________
  • 60,014
  • 4
  • 34
  • 74