O'Reilly logo

C Programming: Visual Quickstart Guide by Marc Liyanage, Larry Ullman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required