c语言编写一个类似于strcat()的字符串连接函数
时间: 2024-01-24 20:05:07 浏览: 27
可以按照下面的代码实现一个类似于strcat()的字符串连接函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *str_concat(char *dest, const char *src)
{
int len_dest = strlen(dest);
int len_src = strlen(src);
char *result = (char *) malloc(len_dest + len_src + 1);
if (result == NULL) {
return NULL;
}
strcpy(result, dest);
strcpy(result + len_dest, src);
return result;
}
int main()
{
char str1[20] = "hello ";
char str2[] = "world!";
char *result = str_concat(str1, str2);
if (result == NULL) {
printf("Error: memory allocation failed.\n");
return 1;
}
printf("The concatenated string is: %s\n", result);
free(result);
return 0;
}
```
在这个函数中,我们首先计算了目标字符串和源字符串的长度,然后使用malloc()函数动态分配足够的内存空间来存储连接后的字符串。接着,我们将目标字符串和源字符串依次复制到新分配的内存空间中,最后返回连接后的字符串的指针。在主函数中,我们调用str_concat()函数连接两个字符串,并在连接成功后打印出连接后的字符串,最后释放分配的内存空间。