“This is the 10th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

Strcpy () function

The library function strcpy() can be used to copy strings in C. Here is an example to illustrate how to use it.

int main(int argc, char *argv[])
{
	char str1[10] = "abcdefg";
	char str2[7] = "123456";
	int ret = 0;
	
	puts(str1);
	puts(str2);
	
	strcpy(str1,str2);	
	
	puts(str1);
	puts(str2);
	
	system("pause");
	return 0;
}
Copy the code

Defines two strings, first printing the contents of both strings, then using the strcpy() function to copy string 2 into string 1. The following output is displayed:

The result shows that everything in string 1 has been replaced by string 2. Make sure that string 1 has enough space to store string 2. Strcpy () does not automatically detect the size of string 1 when copying data. If the space of string 1 does not hold all the characters of string 2, the extra characters may be overwritten into the rest of memory, causing a program exception.

Strncpy () function

To solve the problem that strcpy() does not automatically detect the size of string 1 when copying data, we can use strncpy() when copying data. This function takes one more argument than strcpy(), and the third argument is the size of the data to be copied. The third argument limits the length of characters copied to avoid data overflow problems.

int main(int argc, char *argv[])
{
	char str1[6] = "abc";
	char str2[] = "1234567890";
	int ret = 0;
	
	puts(str1);
	puts(str2);
	
	ret = sizeof(str1);
	printf("%d\r\n",ret);
	
	strncpy(str1,str2,ret);	
	
	puts(str1);
	puts(str2);
	
	system("pause");
	return 0;
}
Copy the code

The sizeof string 1 is calculated by strncpy(), and the sizeof string 1 is reduced by 1 as the third parameter. Since the last bit of a string must be a null character ‘\0’, and sizeof() takes the last empty character into account when calculating the sizeof the string, it is necessary to reserve a space for a null character in string 1.

The print result is as follows:

The length of string 1 is 6, and the space that can be copied is 5 if one blank character is reserved. Therefore, when copying string 2 to string 1, only 5 characters are copied to ensure that the copied characters will not overflow.

The strncpy() function is safer for copying strings.