foreword
The strcpy function is the only way for beginners in the entire C language, so this issue will bring a detailed explanation of the use of strcpy, and the next issue will be a detailed explanation of strlen. If you like it, please pay attention and like it
As we can see in this cplusplus, this strcpy function is a function of copying strings and has a return value
Example:
strcpy (function to be copied, function to be copied)
This is not thorough enough, let's go directly to the code
#include<string.h>
int main()
{
char arr1[20] = { 0 };
char arr2[] = "hello world";
strcpy(arr1, arr2);
printf("%s", arr1);
return 0;
}
In the process of copying, we can know that '\0' can be copied
The above is just the most basic method, but this method is obviously incomplete, let’s take an advanced version
Advanced:
#include <stdio.h>
#include <assert.h>
void my_strcpy(char* dest, char* src)
{
assert(src != NULL && dest != NULL);
while (*dest++ = *src++)
{
;
}
}
int main()
{
char arr1[20] = { 0 };
char arr2[] = "hello world";
my_strcpy(arr1, arr2);
printf("%s", arr1);
return 0;
}
We will find that "assertion" appears in the advanced , the purpose is to prevent the null pointer, and use the assertion
If it is passed as a null pointer, the compiler will automatically report an error here, and we quickly found the error
Final version:
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest,const char* src)
{
assert(dest && src);//断言
char* ret = dest;
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = {0};
char arr2[] = "hello world";
my_strcpy(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
Here we add const before *src . This const mainly means "lock" . If we write src and dest in reverse during compilation, and we use the const function, the compiler will automatically report an error.
const function:
Here we want to explain that the expressions of const char* src and char const* src have the same meaning
const is placed on the left side, *p cannot be changed, but p can be changed (it is just the opposite when placed on the right side)
The above is our explanation today, if you like it, please support it three times, your support is my biggest motivation! ! !