0

The question is to input one string per line (<10 for each) include whitespace possibly and put the first n chars of the second string behind of the first string. And I tried many times using different input function and there are differences between them. I wonder why ? Input like this:

hello
c world
3

Wanted: helloc w

#include<string.h>
void fun(char *s1, char *s2, int n) {
    int l = strlen(s1);
    for(int i=0;i<n;i++) {
        s1[l+i]=s2[i];
    }
    int m=strlen(s1);
    s1[m]='\0'; //It doesnot work.Because when it is not here the outcome is the same.Both `fgets` and `gets` 
}
int main()
{   char s1[10];char s2[8]; int n;
    gets(s1);
    gets(s2);
    scanf("%d",&n);
    fun(s1,s2,n);
    printf("%s",s1);
    return 0; //This is the only one output right.
}

BUt if

char s2[10];//output is :helloc w?@   What is different,why the length of string influence the output.

if

char s2[8];
fgets(s1,10,stdin);
fgets(s2,8,stdin);
//output:
hello
c w

why fgets influence the format of output
  • 5
    I won't be the first to say, do not *ever* use `gets`. – Jeff Holt Jul 20 '21 at 02:15
  • 4
    You may want to read this: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/12149471) – Andreas Wenzel Jul 20 '21 at 02:24
  • 3
    The string `c world` is 7 characters long, and thus requires an array of size 8 to hold it. Attempting to write the string `c world` into `s2` when `s2` is of size 7 is undefined behavior, since you are writing outside the bounds of the array. – William Pursell Jul 20 '21 at 02:42
  • 2
    Just as a side note: If `s2` has a size of 8, then you should not write `fgets(s2,10,stdin);`. Instead, you should write `fgets(s2,8,stdin);` or simply `fgets(s2,sizeof s2,stdin);`. Otherwise, you will write past the end of the memory buffer if the user enters too many characters. – Andreas Wenzel Jul 20 '21 at 02:56
  • 1
    One difference between `gets` and `fgets` is that `gets` does not store the newline character into the string, whereas `fgets` does. That is why you need space for an extra character in the string. Also, when printing the string, you will also print the newline character (unless you [remove it](https://stackoverflow.com/q/2693776/12149471) beforehand). – Andreas Wenzel Jul 20 '21 at 03:43

1 Answers1

2

You should write in: fun(...):

int m = n + l;

Instead of:

int m = strlen(s1);

This is a mistake because strlen requires a null-terminated string, but the null character was overwritten with another character. Therefore, the string is no longer null-terminated. The new null terminator will only be written in the next line.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Wojciech
  • 111
  • 2