用C语言指针编写一个字符串复制的函数
时间: 2024-05-05 11:22:55 浏览: 19
下面是一个用C语言指针编写的字符串复制函数:
```c
#include <stdio.h>
void copy_string(char *target, char *source);
int main() {
char source[100] = "Hello, World!";
char target[100];
copy_string(target, source);
printf("Source string: %s\n", source);
printf("Target string: %s\n", target);
return 0;
}
void copy_string(char *target, char *source) {
while (*source) {
*target = *source;
source++;
target++;
}
*target = '\0';
}
```
在这个函数中,我们使用了指针来迭代源字符串中的每个字符,并将其复制到目标字符串中。在循环中,我们首先将源字符复制到目标字符的位置,然后将指针向前移动一位。最后,我们在目标字符串的结尾插入一个空字符,以确保该字符串以空字符结尾,这是C语言字符串的要求之一。
相关问题
C语言,编写一段函数实现字符串的复制
以下是一个简单的 C 语言函数,可以实现字符串的复制:
```c
void string_copy(char *source, char *destination) {
while (*source) {
*destination = *source;
source++;
destination++;
}
*destination = '\0';
}
```
这个函数使用指针来遍历源字符串中的字符,并将它们复制到目标字符串中,直到遇到字符串结尾标志 '\0'。请注意,此函数假定目标字符串已经足够大,以便保存源字符串的所有字符。如果目标字符串不够大,可能会导致缓冲区溢出和未定义行为。
c语言编写一个类似于strcat()的字符串连接函数
可以按照下面的代码实现一个类似于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()函数连接两个字符串,并在连接成功后打印出连接后的字符串,最后释放分配的内存空间。