strcpy
原库函数用法
#include <stdio.h> #include <string.h> int main() { char arr1[20] = { "xxxxxxxxxxxxxx" }; char arr2[10] = { "hello" }; //arr1为目标空间的起始地址,arr2为要源空间的起始地址 strcpy(arr1, arr2); //运行之后将arr2复制到arr1中(包括‘\0’) printf("%s\n", arr1); return 0; }
模拟函数
#include <stdio.h> #include <assert.h> char* my_strcpy(char* strDestination, const char* strSource)//const防止源空间初始地址被修改 { assert(strSource != NULL);//断言 assert(strDestination != NULL);//断言 //此处断言是为了目标空间初始地址或源空间初始地址为空指针时能够准确报错 char* ret = strDestination;//还原库函数,有返回值 while (*strDestination++ = *strSource++) ;//hello的拷贝 return ret; } int main() { char arr1[20] = { "xxxxxxxxxxxxxx" }; char arr2[10] = { "hello" }; printf("%s\n", my_strcpy(arr1,arr2)); return 0; }
其最终运行结果都为:
知识点复习
const修饰变量,这个变量就被称为常变量,不能被修改,但是本质上还是变量
int main() { const int i; const int* p; int *const b; int const* const pb; i = 10;//error *p = 10;//error b = &i;//error *pb = 20;//error pb = &i;//error return 0; }
strlen
原库函数用法
#include <stdio.h> #include <string.h> int main() { char arr[] = { "indispensable" }; printf("leng = %d\n", strlen(arr)); return 0; }
模拟函数
#include <stdio.h> #include <assert.h> //size_t -- unsigned int size_t my_strlen(const char* strDestination) { assert(strDestination != NULL);//assert(strDestination); size_t count = 0; while (*strDestination++ != '\0') count++; return count; } int main() { char arr[] = { "indispensable" }; printf("leng = %d\n", my_strlen(arr)); return 0; }
其运行结果都为:
知识点复习
C语言库里面重定义了unsigned int
typedef unsigned int size_t;
typedef为现有类型引入了一个新名称,下面看一下MSDN给出的例子
//第一个 typedef unsigned long ulong; ulong ul; // 相当于 "unsigned long ul;" //第二个 typedef struct mystructtag { int i; float f; char c; } mystruct; mystruct ms; //相当于 "struct mystructtag ms;" //第三个 typedef int (*funcptr)(); // funcptr 表示指向函数整型返回值 funcptr table[10]; // 相当于 "int (*table[10])();"
strcat
原库函数用法
#include <stdio.h> #include <string.h> int main() { char arr1[100] = { "love " }; char arr2[100] = { "and " }; char arr3[100] = { "peace " }; strcat(arr1, arr2); strcat(arr1, arr3); printf("%s\n", arr1); return 0; }
模拟函数
#include <stdio.h> #include <assert.h> char* my_strcat(char* strDestination, const char* strSource) { assert(strSource != NULL);//断言 assert(strDestination != NULL);//断言 char* ret = strDestination; while (*strDestination) *strDestination++; while (*strDestination++ = *strSource++) ; return ret; } int main() { char arr1[100] = { "love " }; char arr2[100] = { "and " }; char arr3[100] = { "peace " }; my_strcat(arr1, arr2); my_strcat(arr1, arr3); printf("%s\n", arr1); return 0; }
其运行结果都为: