Search code examples
carraysmemmove

C language wrong output of memove() function?


can't figure out why i got this output from this code.

#include<stdio.h>
#include<string.h>
int main()
{
    char str[] = "I live in NY city";

    printf("%s%s\n","The string in array str[] before invokihg the function memmove(): ",str);

    printf("%s%s\n","The string in array str[] before invokihg the function memmove(): ",memmove(str,&str[7],10));
        return 0;
}

My output is : in NY cityNY city
isn't that should be : in NY city i live ??

Here is similar example from my book and it make sense tho.

#include<stdio.h>
#include<string.h>
int main()
{
    char x[] = "Home Sweet Home";

    printf("%s%s\n","The string in array x[] before invoking the function memmove(): ",x);

    printf("%s%s\n","The string in array x[] before invoking the function memmove(): ",memmove(x,&x[5],10));
        return 0;
}   

And the output here is: Sweet Home Home
Which is right according to definition of memmove() function, that is, copying a specified number of bytes from the object pointed to by its second argument into the object pointed to by its first argument.(withing the same string) Also object here refers to a block of data.


Solution

  • Your expectations are wrong.

    You define a string:

    char str[] = "I live in NY city";
    

    Then you move (copy) 10 bytes from the end to the beginning of the string:

    "I live in NY city\0";
     012345678901234567
           /        /
          /        /
         /        /
        /        /
       /        /
      /        /
    "in NY cityNY city\0";
    

    Everything else is not touched.