01 | #include <stdio.h> |
02 | #include <string.h> |
03 |
04 | void CloneStr( char **dest, const char *src) |
05 | { |
06 | size_t len = strlen (src); |
07 | *dest = new char [len + 1]; |
08 |
09 | char *tDest = *dest; |
10 | while (*src) |
11 | { |
12 | *tDest = *src; |
13 | ++tDest; |
14 | ++src; |
15 | } |
16 | *tDest = '\0' |
17 | } |
18 |
19 | int main( int argc, char *argv[]) |
20 | { |
21 | const char *src = "hoge" ; |
22 | char *dest = NULL; |
23 |
24 | CloneStr(&dest, src); |
25 | printf ( "%s\n" , dest); |
26 |
27 | delete [] dest; |
28 | dest = NULL; |
29 |
30 | return 0; |
31 | } |
※ 追記
strdupという関数があるそうです。知らんかった。
01 | #include <stdio.h> |
02 | #include <stdlib.h> |
03 | #include <string.h> |
04 |
05 | int main( int argc, char *argv[]) |
06 | { |
07 | const char *src = "hoge" ; |
08 |
09 | // 文字列をクローン |
10 | char *dest = strdup(src); |
11 |
12 | //出力 |
13 | printf ( "%s\n" , dest); |
14 |
15 | //メモリ解放 |
16 | free (dest); |
17 | dest = NULL; |
18 |
19 | return 0; |
20 | } |
0 件のコメント:
コメントを投稿