Problem Copying String into Another String

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stdq
    New Member
    • Apr 2013
    • 94

    #1

    Problem Copying String into Another String

    Hello, everyone. I wrote my version of function strcpy, called strcpyUsingPoin ter, that is supposed to copy parameter s2 into parameter s1, and return s1. I also wrote a main function to test it:

    Code:
    #include <stdio.h>
    
    /* Function prototypes: */
    char *strcpyUsingPointer( char *s1, const char *s2 );
    
    int main( void )
    {
        char string1[ 6 ];
        char string2[ 6 ] = "house";
        
        printf( "string2 is %s.\n", string2 );
        
        printf( "strcpyUsingPointer( string1, string2 ) returned %s.\n",
            strcpyUsingPointer( string1, string2 ) );
        
        printf( "string1 is %s.\n", string1 );
        
        /* Successful program termination: */
        return 0;    
    }
    
    /* Copies string s2 into array s1. The value of s1 is returned: */
    char *strcpyUsingPointer( char *s1, const char *s2 )
    {
        int i;
        
        for ( i = 0 ; *( s2 + i ) != NULL ; i++ )
        {
            *( s1 + i ) = *( s2 + i );
        }
        
        return s1;
    }
    However, the output is a little unexpected, as shown in the picture attached. Why is this happening? Thanks in advance.
    Attached Files
  • stdq
    New Member
    • Apr 2013
    • 94

    #2
    Problem solved. I forgot to append the terminating null-character ('\0') to end of s1. Thanks again.

    Comment

    Working...