strcat输出是字符串吗
时间: 2023-12-29 21:06:11 浏览: 27
函数fun的实现如下:
void fun(char *p1, char *p2)
{
while (*p1 != '\0') { // 找到p1字符串的末尾
p1++;
}
while (*p2 != '\0') { // 把p2字符串连接到p1字符串的末尾
*p1 = *p2;
p1++;
p2++;
}
*p1 = '\0'; // 在连接后的字符串末尾添加'\0',表示字符串结束
}
调用fun函数的示例代码如下:
char str1[100] = "firststring";
char str2[100] = "secondstring";
fun(str1, str2);
printf("%s", str1);
输出结果为:firststring--secondstring
相关问题
不用strcat函数实现字符串的连接
以下是两种不使用strcat函数实现字符串连接的方法:
方法一:使用指针
```c
#include <stdio.h>
void str_concat(char *s1, char *s2) {
while (*s1) { // 找到s1的结尾
s1++;
}
while (*s2) { // 将s2的字符逐个复制到s1的结尾
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0'; // 在s1的结尾添加'\0'
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
str_concat(s1, s2);
printf("%s\n", s1); // 输出:helloworld
return 0;
}
```
方法二:使用数组下标
```c
#include <stdio.h>
void str_concat(char s1[], char s2[]) {
int i = 0, j = 0;
while (s1[i] != '\0') { // 找到s1的结尾
i++;
}
while (s2[j] != '\0') { // 将s2的字符逐个复制到s1的结尾
s1[i] = s2[j];
i++;
j++;
}
s1[i] = '\0'; // 在s1的结尾添加'\0'
}
int main() {
char s1[100] = "hello";
char s2[] = "world";
str_concat(s1, s2);
printf("%s\n", s1); // 输出:helloworld
return 0;
}
```
c语言字符串strcat
C语言中的字符串拼接函数是strcat(),它的作用是将源字符串追加到目标字符串的末尾。在使用strcat()函数时,需要注意以下几点:
1. 目标字符串必须有足够的空间来存储源字符串,否则会导致内存溢出。
2. 目标字符串必须以'\0'结尾,否则会导致结果不可预测。
3. 源字符串必须以'\0'结尾,否则会导致结果不可预测。
4. strcat()函数返回的是目标字符串的指针。
在引用的代码中,arr1是一个指向字符串常量的指针,它指向的字符串是"hello"。在执行strcat()函数时,由于arr1指向的是一个字符串常量,所以无法修改该字符串,因此会导致程序崩溃。
在引用中,我们可以看到strcat()函数的定义,其中destination是目标字符串,source是源字符串。
在引用的代码中,arr1是一个字符数组,它的大小为20个字节,其中前5个字节是字符串"hello",后面15个字节是字符'X'。在执行strcat()函数时,由于arr1已经以'\0'结尾,所以可以将arr2追加到arr1的末尾,最终输出的结果是"hellobit"。