已知有两个字符串,比如:"hello" , "world". 用指针来实现strcat函数的功能,连接两个字符串,连接后"hello world" (不能直接调用strcat函数).
时间: 2023-07-21 22:06:48 浏览: 129
你可以使用指针来实现`strcat`函数的功能。下面是一个示例代码:
```c
#include <stdio.h>
void strcat_custom(char *str1, char *str2) {
// 将指针移动到str1的末尾
while (*str1) {
str1++;
}
// 将str2的字符逐个拷贝到str1的末尾
while (*str2) {
*str1 = *str2;
str1++;
str2++;
}
// 在连接的字符串末尾添加NULL字符
*str1 = '\0';
}
int main() {
char str1[50] = "hello";
char str2[] = " world";
strcat_custom(str1, str2);
printf("连接后的字符串:%s\n", str1);
return 0;
}
```
这里定义了一个自定义的`strcat_custom`函数,它使用指针来实现字符串的连接。首先,使用一个指针将其移动到第一个字符串的末尾。然后,使用另一个指针将第二个字符串的字符逐个拷贝到第一个字符串的末尾。最后,添加一个NULL字符来表示字符串的结束。在主函数中,我们将两个字符串传递给`strcat_custom`函数,并打印连接后的字符串。
输出结果为:`连接后的字符串:hello world`。