编写一个字符串拷贝函数
时间: 2023-06-03 16:06:48 浏览: 66
好的,我可以为您编写一个字符串拷贝函数,以下是函数的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* string_copy(const char* source) {
size_t length = strlen(source) + 1;
char* destination = (char*)malloc(length * sizeof(char));
if (destination == NULL) {
return NULL;
}
memcpy(destination, source, length);
return destination;
}
int main() {
char* source = "Hello, World!";
char* destination = string_copy(source);
if (destination != NULL) {
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
free(destination);
}
return 0;
}
```
该函数的功能是将一个字符串复制到另外一个空间中,可以确保两个字符串不会相互干扰。注意,该函数使用了动态内存分配,因此需要记得在使用完成后手动释放内存。