c语言函数调用的方式写一个函数将2个字符串连接成一个字符串。使用字符串数组
- C语言函数调用的方式:
在C语言中,函数调用的方式有两种:
1.1. 值传递(传递参数的值):
在函数调用时,将实际参数的值复制给形式参数,函数中对形式参数的操作不会影响实际参数的值。
例如:
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
swap(x, y);
printf("x=%d, y=%d\n", x, y); // 输出:x=10, y=20
return 0;
}
1.2. 引用传递(传递参数的地址):
在函数调用时,将实际参数的地址传递给形式参数,函数中对形式参数的操作会影响实际参数的值。
例如:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("x=%d, y=%d\n", x, y); // 输出:x=20, y=10
return 0;
}
- 将2个字符串连接成一个字符串的函数实现:
#include <stdio.h>
#include <string.h>
void strconcat(char dest[], char src[]) {
int len_dest = strlen(dest);
int len_src = strlen(src);
int i, j;
for (i = len_dest, j = 0; j < len_src; i++, j++) {
dest[i] = src[j];
}
dest[i] = '\0';
}
int main() {
char s1[100] = "hello";
char s2[100] = "world";
strconcat(s1, s2);
printf("%s\n", s1); // 输出:helloworld
return 0;
}
说明:
该函数的参数为两个字符串数组,分别表示目标字符串和源字符串。
函数中使用了字符串库函数strlen()来获取字符串的长度。
在循环中,将源字符串中的每个字符依次拷贝到目标字符串的末尾。
最后,将目标字符串的末尾设置为结束符\0。
原文地址: https://www.cveoy.top/t/topic/b4qt 著作权归作者所有。请勿转载和采集!