C - String String Copying


strcpy_s() function copies the contents of one string variable to another.

  • The first argument identifies the destination for the copy
  • The second argument is an integer specifying the size of the first argument
  • The third argument is the source string.

Here's an example:

char source[] = "test test test.";
char destination[50];
if(strcpy_s(destination, sizeof(destination), source))
  printf("An error occurred copying the string.\n");

The condition of if statement is an expression that calls strcpy_s() to copy the contents of the source array.

The value of the expression is the value returned by strcpy_s().

This will be 0 if the copy works and nonzero if it doesn't.

A nonzero integer value corresponds to true, the printf() call will be executed to output an error message.

strncpy_s() function can copy part of the source string to the destination.

The first three arguments are the same as for strcpy_s(), and the fourth argument specifies the maximum number of characters to be copied.

If a \0 is found in the source string before the maximum specified characters have been copied, copying ceases and the \0 is appended to the destination.

char source[] = "this is a test test test test test test.";
char destination[50];
if(strncpy_s(destination, sizeof(destination), source, 17))
  printf("An error occurred copying the string.\n");