6-25 D字符串的創建函數 (5分)
D字符串是動態分配內存的字符串,它也采用char
數組來保存字符串中的字符,但是這個數組是在堆中動態分配得到的。
本題要求編寫D字符串的創建函數。
函數接口定義:
char *dstr_create(const char *s);
dstr_create
用輸入的字符串s的內容創建一個新的字符串。
裁判測試程序樣例:
#include <stdio.h> #include <stdlib.h> #include <string.h> // 該函數由系統提供 char *dstr_readword(); char *dstr_create(const char *s); int main() { char *s = dstr_create("hello"); printf("%lu-%s\n", strlen(s), s); free(s); char *t = dstr_readword(); s = dstr_create(t); free(t); printf("%lu-%s\n", strlen(s), s); free(s); } /* 請在這里填寫答案 */
輸入樣例:
123A
輸出樣例:
5-hello
4-123A
char *dstr_create(const char *s)
{
int str;
str=strlen(s);
char *p=malloc(str*sizeof(char)+1);
strcpy(p,s);
return p;
}