通过指针来实现两个字符数组的连接 不能用库函数 要用子函数
时间: 2023-12-24 14:03:37 浏览: 40
可以通过以下的子函数来实现两个字符数组的连接:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void str_concat(char *str1, char *str2) {
while (*str1) {
str1++;
}
while (*str2) {
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}
int main() {
char str1[100], str2[100];
printf("Input string 1: ");
scanf("%s", str1);
printf("Input string 2: ");
scanf("%s", str2);
str_concat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
```
在这个程序中,我们定义了一个名为`str_concat`的子函数,它接受两个字符数组作为参数,然后将第二个字符数组连接到第一个字符数组的末尾。具体来说,我们先将指针`str1`移动到第一个字符数组的末尾,然后通过循环将指针`str2`指向的字符一个一个地复制到`str1`指向的位置,直到`str2`指向的字符为`\0`(表示字符串的结尾)。最后,我们将`str1`指向的位置设置为`\0`,以确保连接后的字符串也以`\0`结尾。
在`main`函数中,我们首先读入两个字符数组,然后调用`str_concat`函数将它们连接起来,最后打印结果。
需要注意的是,这个程序中使用了标准库函数`scanf`来读入字符串,但是在实际的开发中,为了避免缓冲区溢出和其他安全问题,我们应该使用`fgets`函数来读入字符串。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)