'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 ?
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=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; strncpy(dest,"Hello world",3); dest=tmp; as opposed to the clearer code in the event that you do want NULL appending: strncpy(dest,"Hello world",3); dest=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 13:14.|