To recreate strcpy

This is a discussion on To recreate strcpy within the C Programming forums, part of the General Programming Boards category; Code: char* new_strcpy(char* destination,const char* source) { int i=0; while(*(source+i)!='

Thread: To recreate strcpy

') { *(destination+i)= *(source+i); i++; } *(destination+i)='

Thread: To recreate strcpy

';//line return destination; } char* ...

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    35

    To recreate strcpy

    Code:
    char* new_strcpy(char* destination,const char* source)
    {
      int i=0;
      while(*(source+i)!='\0')
      {
        *(destination+i)= *(source+i);
        i++;
      }
      *(destination+i)='\0';//line
      return destination;
    
    }
    
    char* new_strncpy(char* destination,const char* source,size_t n)
    {
       int i=0;
      while(i!=n)
      {
        *(destination+i)= *(source+i);
        i++;
      }
      *(destination+i)='\0';//line
      return destination;
      
    }
    My Question :
    If we are trying to copy from source to a destination with my while condition would a '\0' be copied to destination? or would I need the (comment marked line)separately.

  2. #2
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    Just ask yourself what the while loop is doing. The loop stops when the '0' is encountered, right ? So, no copying is done in that iteration.
    In the middle of difficulty, lies opportunity

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Code:
    char* new_strncpy(char* destination,const char* source,size_t n)
    {
       int i=0;
      while(i!=n)
      {
        *(destination+i)= *(source+i);
        i++;
      }
      *(destination+i)='\0';//line
      return destination;
      
    }
    What if n > strlen(source)?
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    May 2007
    Posts
    58
    Code:
    void strcpy(char* dest, const char* source)
    {
          while((*(dest++) = *(char++)) != '\0');
    }
    =)

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >while((*(dest++) = *(char++)) != '\0');
    Despite the fact that a lot of people think this kind of thing is "cool", it's typically a weaker solution because some compilers have difficulty optimizing complicated statements with side effects, and it's easy to get the statements wrong when they're more complex. Not to mention that it makes life harder for you if you want to optimize the function into a block copy instead of a byte copy:
    Code:
    /* Check for an incomplete block for string block copying */
    #define has_nul(x) (((x) - 0x01010101) & ~(x) & 0x80808080)
    
    /*
      32-bit block copy for strings
      Sets input parameters to the first incomplete block
    */
    #define block_copy(dst,src) do {   \
      long int *to = (long int*)dst;   \
      long int *from = (long int*)src; \
      while ( !has_nul ( *from ) ) {   \
        *to = *from;                   \
        ++to;                          \
        ++from;                        \
      }                                \
      dst = (char*)to;                 \
      src = (char*)from;               \
    } while ( 0 )
    
    #define byte_copy(dst,src) do { \
      while ( *src != '\0' ) {      \
        *dst = *src;                \
        ++dst;                      \
        ++src;                      \
      }                             \
      *dst = '\0';                  \
    } while ( 0 )
    
    char *jsw_strcpy ( char *dst, const char *src )
    {
      char *save = dst;
    
      /* Do as much as we can with a block copy */
      block_copy ( dst, src );
    
      /* Finish the last incomplete block */
      byte_copy ( dst, src );
    
      return save;
    }
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    Jan 2007
    Posts
    72
    this is your responsability to copy \0 in the distination as long as you copy one character each. cause it's the only differnce between a string and an array of caracters.
    proud to be from aui www.aui.ma and also a great elton john's fan

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    Beware of block copies too though:
    They can be faster, but if the source and destination are not both aligned on a 4-byte boundary, then it could quite possibly be slower. In fact on some architectures such as 680x0, reading from an unaligned address will cause a hardware execption, so it isn't totally portable.
    Byte copies also win for smaller strings of course too.

    Actually I'd go for something pretty close to what Govalant posted, myself.

    OP: So why replace strcpy anyway? I have had to write replacement variants of it myself for some embedded compiler, but that was a pretty rare need...
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >so it isn't totally portable.
    Of course not. But an implementation's strcpy can be written to take advantage of the target platform without worrying about portability. The code I posted isn't meant to run fast (or even work) everywhere.

    >Actually I'd go for something pretty close to what Govalant posted, myself.
    Me too. It's probably not worth the effort of writing anything more sophisticated.
    My best code is written with the delete key.

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    Quote Originally Posted by Prelude View Post
    >so it isn't totally portable.
    Of course not. But an implementation's strcpy can be written to take advantage of the target platform without worrying about portability. The code I posted isn't meant to run fast (or even work) everywhere.
    Hmm, very good point.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  10. #10
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >OP: So why replace strcpy anyway?
    I think it's a common exercise.

  11. #11
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    I had a go a re-writing a load of functions featured in <string.h>. Initially I thought there would at least be the benefit of a smaller exe, but I have since learnt that some clever compilers only include the stuff thats used making this kind of stuff, well... Useless.

    Still it was fun to code.
    Code:
    void ToUpper(char*s){ while(*s){if(*s>='a'&&*s<='z')*s-=32;s++;} }
    void ToLower(char*s){ while(*s){if(*s>='A'&&*s<='Z')*s+=32;s++;} }
    int Len(char *s) { int i; while(*s){i++;*s++;} return i; } 
    int GetS(char *st, int sz) { fgets(st, sz, stdin); int l=Len(st)-1; st[l]='\0'; return l; } 
    
    int StrCmp(char *s1, char *s2) 
    {   
        while(*s1 || *s2) 
        { 
            if(*s1 > *s2 || ! *s2) return-1; 
            if(*s1 < *s2 || ! *s1) return 1;
            *s1++; *s2++;
        }                 
        return 0;         
    }

  12. #12
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,239
    Quote Originally Posted by mike_g View Post
    Still it was fun to code.
    Code:
    int StrCmp(char *s1, char *s2) 
    {   
        while(*s1 || *s2) 
        { 
            if(*s1 > *s2 || ! *s2) return-1; 
            if(*s1 < *s2 || ! *s1) return 1;
            *s1++; *s2++;
        }                 
        return 0;         
    }
    I'm not sure about those inner tests. I'd perform the null check first:

    Code:
    if(!*s2 || *s1 > *s2) return -1;
    if(!*s1 || *s1 < *s2) return 1;
    Otherwise you end up comparing one of the characters with the null byte, which, while probably harmless, doesn't "feel right."

    EDIT: Also, aren't those comparisons reversed from how they should be?

  13. #13
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    I'm not sure about those inner tests.
    From what it says in my C++ book the ! operator has higher precedence than: ||, >, and <. From that I presumed that the if statement sequence would run the 'not' check first, but maybe I was wrong about that.

    Also, aren't those comparisons reversed from how they should be?
    Probably. I was never really sure which was the positive/negative way round. It seemed to work, but I guess I should have tested it a bit better.

  14. #14
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,239
    Quote Originally Posted by mike_g View Post
    From what it says in my C++ book the ! operator has higher precedence than: ||, >, and <. From that I presumed that the if statement sequence would run the 'not' check first, but maybe I was wrong about that.
    Logical OR is short-circuiting, which means the left side argument will be fully evaluated before the right side argument.

  15. #15
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Ok. Thanks, I'll remember that.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A Full Program to analyze.
    By sergioms in forum C Programming
    Replies: 2
    Last Post: 12-30-2008, 08:42 AM
  2. Strcpy
    By Godders_2k in forum C Programming
    Replies: 17
    Last Post: 12-12-2007, 11:34 AM
  3. Where is strcpy() defined? (Can't find in string.h ect)
    By Zero_Point in forum C++ Programming
    Replies: 6
    Last Post: 04-03-2006, 05:14 PM
  4. Question about strcpy
    By Kevinmun in forum C Programming
    Replies: 4
    Last Post: 11-02-2005, 10:00 PM
  5. strcpy
    By Luigi in forum C++ Programming
    Replies: 17
    Last Post: 02-16-2003, 03:11 PM