1. assert(src !=NULL)
注解:这里的 assert 表示断言(如果assert后面的为真则不报错,否则报错),文中所要表达的意思是:如果指针 src 不为空指针(NULL,NULL对应的(十进制)值就是0),则不报错,否则报错。assert一般用在解引用前,之所以要判断是因为src 为空指针时解引用会出现问题;
2.const int* p;//const 修饰的是 *p,表达的意思是外界不再能赋值给 *p(言外之意外界可以赋值给p)
int* const p;//const 修饰的是 p,表达的意思是外界不再能赋值给 p(言外之意外界可以赋值给*p)
const int* const p;//左边 const 修饰的是 *p,右边 const 修饰的是 p,左边 const 表达的意思是外界不再能赋值给 *p,右边 const 表达的意思是外界不再能赋值给 p(言外之意外界无法赋值给*p 和 p)
例1:模拟实现库函数:strcpy(strcpy复制字符串,包括\0)
//模拟实现库函数:strcpy(strcpy复制字符串,包括\0)
#include <stdio.h>
#include <assert.h>
void my_strcpy(char* arr3, const char* arr4)
{
assert(arr3 && arr4);
while (*arr3++ = *arr4++)
{
}
}
int main()
{
char arr1[] = "hello world";
char arr2[100] = { 0 };
my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
例2:模拟实现库函数 strlen(strlen求字符串长度,不包括\0)
//模拟实现库函数 strlen(strlen求字符串长度,不包括\0)
#include <stdio.h>
#include <assert.h>
int my_strlen(const char* arr1)
{
int count = 0;
assert(arr1);
while (*arr1 != '\0')
{
count += 1;
arr1 += 1;
}
return count;
}
int main()
{
char arr[] = "abcdefg";
printf("%d\n", my_strlen(arr));
return 0;
}