C言語で、二つの文字列を連結するプログラムを以下のように書きました。
C
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4 5int main (int count, char* param[]) { 6 7 char* str_a = NULL; 8 char* str_b = NULL; 9 char* my_strconcat(char* a, char* b); 10 if (count > 2) { 11 str_a = param[1]; 12 str_b = param[2]; 13 } else { 14 printf("It is not enough that parameter which you proposed."); 15 exit(2); 16 } 17 char* res = NULL; 18 res = my_strconcat(str_a, str_b); 19 printf("%s", res); 20 return(0); 21} 22 23char* my_strconcat(char* a, char* b) { 24 char* temp = NULL; 25 char* source_p = NULL; 26 int len_a = 0; 27 int len_b = 0; 28 len_a = strlen(a); 29 len_b = strlen(b); 30 temp = realloc(a, len_a + len_b); 31 if (temp != NULL) { 32 a = temp; 33 source_p = a; 34 } else { 35 printf("The application failed the command."); 36 exit(2); 37 } 38 // \0を示すインデックスまでポインタを進める 39 a = a + len_a; 40 int i = 0; 41 while(1) { 42 if (*(b) != '\0') { 43 *a = *(b); // (1)ここで第一引数のポインタ変数に第二引数の文字を代入(コピー)して文字列を拡張 44 a = a + 1; 45 b = b + 1; 46 } else { 47 break; 48 } 49 i++; 50 } 51 *a = '\0'; 52 free(a); 53 return (source_p); 54}
ふと疑問に思ったのですが、(1)の第一引数のポインタが指し示すヌル文字に第二引数の最初の文字を代入していきますが、Javaやpythonなどの文字列はイミュータブルだと聞いたのですが
C言語では上記のように任意の文字列リテラルの任意の位置の文字を差し替えるなどしても問題ないのでしょうか?
AtsushiSaitoさんから
mallocしていないポインタをreallocすることは不適切だとの指摘を受けたので
修正してみました。
C
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4 5int main (int count, char* param[]) { 6 7 char* str_a = NULL; 8 char* str_b = NULL; 9 char* my_strconcat(char* a, char* b); 10 if (count > 2) { 11 str_a = param[1]; 12 str_b = param[2]; 13 } else { 14 printf("It is not enough that parameter which you proposed."); 15 exit(2); 16 } 17 char* res = NULL; 18 res = my_strconcat(str_a, str_b); 19 printf("%s", res); 20 return(0); 21} 22 23char* my_strconcat(char* a, char* b) { 24 char* temp = NULL; 25 char* source_p = NULL; 26 int len_a = 0; 27 int len_b = 0; 28 len_a = strlen(a); 29 len_b = strlen(b); 30 temp = malloc(len_a + len_b); 31// temp = realloc(a, len_a + len_b); 32 if (temp != NULL) { 33 source_p = temp; 34 } else { 35 printf("The application failed the command."); 36 exit(2); 37 } 38 39 int i = 0; 40 while(1) { 41 if (*a != '\0') { 42 *temp = *a; 43 temp++; 44 a++; 45 } else if (*a == '\0') { 46 if (*(b) != '\0') { 47 *temp = *(b); 48 temp++; 49 b++; 50 } else { 51 break; 52 } 53 } 54 } 55 *temp = '\0'; 56 return (source_p); 57}
reallocをmallocに変えて 引数に渡った2つの文字列を一バイトずつ
コピーしました。
ちょっとというかかなり冗長になってますが,Cのポインタ操作としては問題ないでしょうか?
回答5件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/27 15:32
2017/07/27 16:13