本實例演示如何使用 malloc 動態分配內存,將兩個輸入字符串拼接為一個新字符串並返回。
strconnect 函數根據兩字符串長度分配足夠內存(含結束符)。strcat 依次拼接,返回指向新內存的指針。// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
char* strconnect(char *str1, char *str2);
int main() {
char str1[20], str2[20];
char *str;
puts("請輸入兩個字符串,用回車分開:");
gets(str1);
gets(str2);
str = strconnect(str1, str2);
puts("連接後的字符串為:");
puts(str);
system("pause");
return 0;
}
char* strconnect(char *str1, char *str2) {
char *str;
str = (char*)malloc(strlen(str1) + strlen(str2) + 1);
str[0] = '\0';
strcat(str, str1);
strcat(str, str2);
return str;
}
free(str) 釋放內存,否則會內存洩漏。malloc 返回值是否為 NULL。gets() 不安全,請改用 fgets()。