Copying Strings
Sometimes you'll need to create a copy of a string in an application so that you can manipulate the value without affecting the original. When you work with strings and pointers, you have two ways of copying strings. The first method makes use of the strncpy() function:
strncpy(string1, string2, length);
Once again, the length value should correspond to the available room in string1. This function makes a literal copy of the value of string2 and assigns this to string1.
The strncpy() is fine when you want a second copy of a string, but it does require twice the memory, as that second string must also be stored. If you want to work with a second reference to a string value instead, you can copy a string pointer:
char *string1 ...
Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.