質問するログイン新規登録

質問編集履歴

1

reallocをしている箇所をただしくmallocでメモリ確保しました。

2017/07/27 13:51

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -59,4 +59,73 @@
59
59
  ```
60
60
 
61
61
  ふと疑問に思ったのですが、(1)の第一引数のポインタが指し示すヌル文字に第二引数の最初の文字を代入していきますが、Javaやpythonなどの文字列はイミュータブルだと聞いたのですが
62
- C言語では上記のように任意の文字列リテラルの任意の位置の文字を差し替えるなどしても問題ないのでしょうか?
62
+ C言語では上記のように任意の文字列リテラルの任意の位置の文字を差し替えるなどしても問題ないのでしょうか?
63
+
64
+ AtsushiSaitoさんから
65
+ mallocしていないポインタをreallocすることは不適切だとの指摘を受けたので
66
+ 修正してみました。
67
+
68
+
69
+ ```C
70
+ #include <stdio.h>
71
+ #include <stdlib.h>
72
+ #include <string.h>
73
+
74
+ int main (int count, char* param[]) {
75
+
76
+ char* str_a = NULL;
77
+ char* str_b = NULL;
78
+ char* my_strconcat(char* a, char* b);
79
+ if (count > 2) {
80
+ str_a = param[1];
81
+ str_b = param[2];
82
+ } else {
83
+ printf("It is not enough that parameter which you proposed.");
84
+ exit(2);
85
+ }
86
+ char* res = NULL;
87
+ res = my_strconcat(str_a, str_b);
88
+ printf("%s", res);
89
+ return(0);
90
+ }
91
+
92
+ char* my_strconcat(char* a, char* b) {
93
+ char* temp = NULL;
94
+ char* source_p = NULL;
95
+ int len_a = 0;
96
+ int len_b = 0;
97
+ len_a = strlen(a);
98
+ len_b = strlen(b);
99
+ temp = malloc(len_a + len_b);
100
+ // temp = realloc(a, len_a + len_b);
101
+ if (temp != NULL) {
102
+ source_p = temp;
103
+ } else {
104
+ printf("The application failed the command.");
105
+ exit(2);
106
+ }
107
+
108
+ int i = 0;
109
+ while(1) {
110
+ if (*a != '\0') {
111
+ *temp = *a;
112
+ temp++;
113
+ a++;
114
+ } else if (*a == '\0') {
115
+ if (*(b) != '\0') {
116
+ *temp = *(b);
117
+ temp++;
118
+ b++;
119
+ } else {
120
+ break;
121
+ }
122
+ }
123
+ }
124
+ *temp = '\0';
125
+ return (source_p);
126
+ }
127
+ ```
128
+
129
+ reallocをmallocに変えて 引数に渡った2つの文字列を一バイトずつ
130
+ コピーしました。
131
+ ちょっとというかかなり冗長になってますが,Cのポインタ操作としては問題ないでしょうか?