代码拉取完成,页面将自动刷新
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。