C 语言字符串连接的 3种方式
#include<stdio.h> #include<stdlib.h> #include<string.h> char *join1(char *, char*); void join2(char *, char *); char *join3(char *, char*); int main(void) { char a[4] = "abc"; // char *a = "abc" char b[4] = "def"; // char *b = "def" char *c = join3(a, b); printf("Concatenated String is %s ", c); free(c); c = NULL; return 0; } /*方法一,不改变字符串a,b, 通过malloc,生成第三个字符串c, 返回局部指针变量*/ char *join1(char *a, char *b) { char *c = (char *) malloc(strlen(a) + strlen(b) + 1); //局部变量,用malloc申请内存 if (c == NULL) exit (1); char *tempc = c; //把首地址存下来 while (*a != '