加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
homework_2021_10.27_11.c 2.83 KB
一键复制 编辑 原始数据 按行查看 历史
#include <stdio.h>
#include <string.h>
#include <assert.h>
//写第一题脑子瓦塔了,传进去指针忘了解引用,并且没有让指针进行后移操作
int mystrlen(char* arr) {
assert(arr != NULL);
int len = 0;
while (*arr != '\0') {
arr++;
len++;
}
return len;
}
char* mystrcpy(char* dest, char* source) {
assert(dest != NULL);
assert(source != NULL);
char* head = dest;
while (*source != '\0') {
*dest = *source;
dest++;
source++;
}
*dest = '\0';
return head;
}
//memmove 可以处理内存重叠的问题
void* mymemmove(void* destination, const void* source, size_t num) {
assert(destination != NULL);
assert(source != NULL);
void* ret = destination;
//这里记住void*类型不能运算,判断地址的原因是防止没有赋值的元素被覆盖,即为解决内存重叠的问题
//判断之后才能决定从前往后赋值还是从后往前
if (destination<source || (char*)destination>(char*)source + num) {
while ((long)num != 0) {
(char*)destination = (char*)source;
(char*)destination+=1;
(char*)source += 1;
num--;
}
}
else {
destination = (char*)destination + num - 1;
source = (char*)source + num - 1;
while ((long)num != 0) {
*(char*)destination = *(char*)source;
(char*)destination -= 1;
(char*)source -= 1;
num--;
}
}
return ret;
}
void* mymemcpy(void* destination, const void* source, size_t num) {
assert(destination != NULL);
assert(source != NULL);
void* ret = destination;
for (size_t i = 0; i < num; i++) {
((char*)destination)[i] = ((char*)source)[i];
}
return ret;
}
const char* mystrstr(const char* str1, const char* str2) {
assert(str1 != NULL);
assert(str2 != NULL);
assert(*str1 != '\0');
assert(*str2 != '\0');
char* red = str1;
while (*red != '\0') {
char* s1 = red;
char* s2 = str2;
while(*s1 == *s2&&*s1!='\0'&&*s2!='\0') {
//指向相同往后比较
s1++;
s2++;
}
//这里s1和s2判断顺序有讲究,如果先判断s1的话是不对的,如果找到了字符串,恰好s1s2都指向了反斜杠零
//此时就应该返回正确的指针了如果先判断s1的话就会又red++此时就把正确的答案错过了
if (*s2 == '\0') {
return red;
}
////2.
//else if (*s1 = '\0') {
// red++;
//}
////3.*s1!=*s2
//else {
// red++;
//}
else {
red++;
}
}
return NULL;
}
char* mystrcat(char* dest, const char* src) {
assert(dest != NULL);
assert(src != NULL);
char* p = dest;
while (*dest != '\0') {
dest++;
}
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
return p;
}
int mystrcmp(const char* str1, const char* str2) {
assert(str1!=NULL);
assert(str2!=NULL);
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 < *str2) {
return -1;
}
else if (*str1 > *str2) {
return 1;
}
else {
str1++;
str2++;
}
}
if (*str1 < *str2) {
return -1;
}
else if (*str1 > *str2) {
return 1;
}
else {
return 0;
}
}
int main() {
char arr[20] = "hello";
char arr1[] = "abcdabcdehello";
char* str = mystrcat(arr, arr1);
printf("%s",str);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化