[Advanced C Language: Get to the bottom of string functions] strcpy function

Highlights of this section:

  • In-depth understanding of the use of strcpy function
  • Learn the simulation implementation of the strcpy function

⚡strcpy

  • Copies the C string pointed by source into the array pointed by destination, including the
    terminating null character (and stopping at that point).
  • The source string must be terminated with '\0'.
  • Will copy '\0' in the source string to the target space.
  • The destination space must be large enough to accommodate the source string.
  • The target space must be mutable.

The basic use of strcpy:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main()
{
	char arr1[] = "abcdef";
	char arr2[20] = { 0 };
	strcpy(arr2, arr1);//将arr1的数据拷贝到arr2中
	printf("%s\n", arr2);
	return 0;
}

The result of the operation is as follows:

 Here are a few related examples:

1. The source string must end with '\0', otherwise it cannot be copied correctly.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main()
{
	char arr1[] = { 'a','b','c' };
	char arr2[20] = "xxxxxxxx";
	strcpy(arr2, arr1);
	printf("%s\n", arr2);
	return 0;
}
//此程序会崩溃

2. strcpy will copy '\0' in the source string to the target space.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main()
{
	char arr1[] = "abc\0def";
	char arr2[20] = "xxxxxxxx";
	strcpy(arr2, arr1);
	printf("%s\n", arr2);
	return 0;
}

The result of running the code is as follows:

 3. The destination space must be large enough to accommodate the source string.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main()
{
	char arr1[] = "abcdef";
	char arr2[3] = { 0 };
	strcpy(arr2, arr1);
	printf("%s\n", arr2);
	return 0;
}

 Program error:

 4. The target space must be modifiable.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main()
{
	char* p = "abcdef"; //指针所指向的字符串为常量字符串,其内容不能被修改。
	char arr2[20] = "JX_BC";
	strcpy(p, arr2);
	printf("%s\n", arr2);
	return 0;
}
//该程序会崩溃

⚡Simulate and implement the strcpy function

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<assert.h>

//返回目标空间的起始位置
char* my_strcpy(char* dest, const char* src)//源头的数据不能发生变化,因此加上const进行保护
{
	char* start = dest;
	assert(dest && src);//断言保证两个指针有效
	while (*dest++ = *src++)
	{
		;
	}
	return start;
}

int main()
{
	char arr1[] = "abcdef";
	char arr2[20] = { 0 };
	my_strcpy(arr2, arr1);
	printf("%s\n", arr2);
    //printf("%s\n", my_strcpy(arr2, arr1));
	return 0;
}

The result of running the code is as follows:


Thank you for reading this blog. It took a long time to create it. Friends think my blog is helpful to you. You may wish to leave your likes and favorites, follow me, and show you a different C language.

98b76a6f4a9c4ca88fd93da1188ac6f9.gif

Guess you like

Origin blog.csdn.net/JX_BC/article/details/129538357