Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   'C' Strings Usage (http://www.go4expert.com/forums/c-strings-usage-t14404/)

kanaks_go4ex 7Oct2008 00:12

'C' Strings Usage
 
What is the difference between strcpy & strncpy ?

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

xpi0t0s 7Oct2008 15:10

Re: 'C' Strings Usage
 
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.


All times are GMT +5.5. The time now is 16:27.