今天讲了很有意思的,自己写<string.h>函数库中的一些函数,比如字符串的链接,字符串的比较等等。
有个比较重要的点,全老师说到了,就是在函数调用时一定要先判断指针及字符是否为空。
#include<assert.h>
assert(NULL!=str);
还有const int *p = &a;和int const *p = &a;这两种写法是一样的,封锁i的都是指针的指向能力;
int * const p = &a;修饰的是指针变量自身;
const int * const p = &a;两者都修饰。
今天的作业:
#include<stdio.h>
#include<string.h>
#if 0
int my_strcmp(char* dist, char* src)
{
int num = 0;
if (dist == nullptr || src == nullptr) return -1;
for (;*dist != '\0' || *src != '\0';dist++, src++)
{
if (*dist < *src)
{
num = -2;
break;
}
else if (*dist > *src)
{
num = 1;
break;
}
else if (*dist = *src)
{
num++;
}
}
return num;
}
char* my_strcat(char* dist, char* src)
{
if (dist == nullptr || src == nullptr) return dist;
int num = 0;
int i = 0;
char* pr = dist;
char* lr = src;
while (*pr != '\0')
{
num++;
pr++;
}
while (*lr != '\0')
{
i++;
lr++;
}
for(int j=0;j<i;j++)
{
dist[num + j] = src[j];
}
return dist;
}
/*
char* my_strcpy(char* dist, char* src)
{
if (dist == nullptr || src == nullptr) return dist;
char* cp = dist;
while (*src != '\0')
{
*cp = *src;
cp++;
src++;
}
return dist;
}
int my_strlen(char* str)
{
if (str == nullptr) return -1;
char* cp = str;
while (*cp != '\0')
{
cp++;
}
return cp - str;
}
int my_strlen(const char* str)
{
if (str == nullptr) return -1;
int num = 0;
while (str[num]!= '\0')
{
num++;
}
return num;
}
*/
int main()
{
char stra[20] = { "myming" };
char strc[20] = { "myming"};
char strd[20] = { "myaing" };
char stre[20] = { "myning" };
//int len = my_strlen(stra);
//printf("len %d\n", len);
int m = my_strcmp(stra, strc);
int i = my_strcmp(stra, strd);
int j = my_strcmp(stra, stre);
printf("stra和strc的关系为:%d\n", m);
printf("stra和strd的关系为:%d\n", i);
printf("stra和stre的关系为:%d\n", j);
char strb[20] = { "hello" };
//my_strcpy(strc,my_strcpy(strb, stra));
my_strcat(stra, strb);
printf("%s\n", stra);
printf("%s\n", strb);
return 0;
}
#endif