6-25 D字符串的創建函數 (5分)


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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM