1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

'C' Strings Usage

Discussion in 'C' started by kanaks_go4ex, Oct 6, 2008.

  1. kanaks_go4ex

    kanaks_go4ex New Member

    Joined:
    Jun 11, 2008
    Messages:
    16
    Likes Received:
    0
    Trophy Points:
    0
    What is the difference between strcpy & strncpy ?

    What will be the impact , if NULL value not appended to the end of every string copy ?
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    strcpy copies the full string and strncpy copies a maximum of n characters.
    strcpy(dest,"Hello world") copies "Hello world" including the terminating zero to dest.
    strncpy(dest,"Hello world",3) copies 'H', 'e' and 'l' to dest. If you want it null terminated then you must add dest[3]=0;
    strncpy is useful for preventing buffer overflows.

    Your second question assumes it should be. This is not necessarily the case; you may only want 'H','e','l' copying into dest. If NULL was automatically appended and you didn't want that, you'd end up with something awkward like char tmp=dest[3]; strncpy(dest,"Hello world",3); dest[3]=tmp; as opposed to the clearer code in the event that you do want NULL appending: strncpy(dest,"Hello world",3); dest[3]=0; C was designed (a) to assume the programmer knows what he is doing and (b) to be fast. So functions do exactly what they say on the box, and it's up to you to understand the implications of that.
     

Share This Page