自定义函数将两个字符串连接起来指针实现
时间: 2024-05-05 16:20:58 浏览: 10
可以使用指针实现一个自定义函数,将两个字符串连接起来。以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 自定义函数,将两个字符串连接起来
char* strconcat(char* str1, char* str2) {
int len1 = 0, len2 = 0, i, j;
// 计算 str1 的长度
while (*(str1 + len1) != '\0') {
len1++;
}
// 计算 str2 的长度
while (*(str2 + len2) != '\0') {
len2++;
}
// 分配内存
char* result = (char*)malloc((len1 + len2 + 1) * sizeof(char));
// 拷贝 str1 到 result
for (i = 0; i < len1; i++) {
*(result + i) = *(str1 + i);
}
// 拷贝 str2 到 result
for (j = 0; j < len2; j++) {
*(result + i + j) = *(str2 + j);
}
// 加上字符串结束符
*(result + i + j) = '\0';
return result;
}
int main() {
char str1[] = "Hello, ";
char str2[] = "world!";
char* result = strconcat(str1, str2);
printf("%s\n", result);
free(result); // 释放内存
return 0;
}
```
在上面的代码中,我们先分别计算了两个字符串的长度,然后根据长度分配了内存。接着,使用指针遍历 str1 和 str2,将它们拷贝到 result 中。最后,加上一个字符串结束符,并返回 result。需要注意的是,我们在使用完 result 后,需要手动释放它所占用的内存,以免造成内存泄漏。