|
发表于 2023-10-8 21:00:20
|
显示全部楼层
这段代码存在几个问题:
1. while(*source!= '/0') 应该是 while(*source!= '\0') ,表示当 source 指向的字符不是字符串结束符时,继续执行循环。
2. char* in =mstrcat("abc","def"); 这句代码的问题在于, "abc" 和 "def" 是常量字符串,不能直接修改。应该先定义两个字符数组,再将它们传递给 mstrcat 函数。
3. printf("%s",*in); 应该是 printf("%s",in); ,因为 in 已经是一个指向字符数组的指针,不需要再使用解引用符号 * 。
修改后的代码如下:
- #include <stdio.h>
- #include <string.h>
- char * mstrcat(char* destination, char* source)
- {
- if (destination == NULL)
- {
- return NULL;
- }
- if (source == NULL)
- return destination;
- char * rar = destination;
- while (*destination != '\0')
- {
- destination++;
- }
- while (*source != '\0')
- {
- *destination = *source;
- destination++;
- source++;
- }
- *destination = '\0';
- return rar;
- }
- int main(void)
- {
- char str1[20] = "abc";
- char str2[20] = "def";
- char* in = mstrcat(str1, str2);
- printf("nihao");
- printf("%s", in);
- printf("mina");
- return 0;
- }
复制代码
运行结果为: nihaodefmina |
|