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

回答編集履歴

2

コードの修正

2021/06/05 16:13

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -38,16 +38,16 @@
38
38
  if (p == NULL)
39
39
  printf("\n");
40
40
  else {
41
- printf(" -> %.15g", p->data);
41
+ printf(" -> %g", p->data);
42
42
  show_list(p->next);
43
43
  }
44
44
  }
45
45
 
46
- void free_list(struct cell *q)
46
+ void free_list(struct cell *p)
47
47
  {
48
- if (q->next != NULL)
48
+ if (p == NULL) return;
49
- free_list(q->next);
49
+ free_list(p->next);
50
- free(q);
50
+ free(p);
51
51
  }
52
52
 
53
53
  int main(void)
@@ -57,14 +57,11 @@
57
57
 
58
58
  while (1) {
59
59
  printf("0以上のデータを入力して下さい(負の値で終了) -->");
60
- if (scanf("%lf", &data) != 1 || data < 0) {
60
+ if (scanf("%lf", &data) != 1 || data < 0) break;
61
- free_list(p);
62
- break;
63
- } else {
64
- add_list(&p, data);
61
+ add_list(&p, data);
65
- show_list(p);
62
+ show_list(p);
66
- }
67
63
  }
64
+ free_list(p);
68
65
  return 0;
69
66
  }
70
67
  ```

1

コードを追加

2021/06/05 16:13

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -4,4 +4,68 @@
4
4
  ここで、セグメンテーションフォールトになっても仕方がないのに、偶然どこかの
5
5
  メモリ領域の struct cell の next に NULL を書き込めてしまったようです。
6
6
 
7
- あと、malloc で領域を確保していないのに free をするのも変です。
7
+ あと、malloc で領域を確保していないのに free をするのも変です。
8
+
9
+ **追記**
10
+ 現在のコードはどうなっているのですか?
11
+ 質問に追記してください。
12
+ malloc は使っていますか?
13
+
14
+ また、次のコードを参考にして、あなたのコードに活用できませんか?
15
+ ```C
16
+ #include <stdio.h> // scanf, printf
17
+ #include <stdlib.h> // malloc, free
18
+
19
+ struct cell {
20
+ double data;
21
+ struct cell *next;
22
+ };
23
+
24
+ void add_list(struct cell **q, double a)
25
+ {
26
+ if (*q != NULL && (*q)->data < a)
27
+ add_list(&(*q)->next, a);
28
+ else {
29
+ struct cell *p = malloc(sizeof(struct cell));
30
+ p->data = a;
31
+ p->next = *q;
32
+ *q = p;
33
+ }
34
+ }
35
+
36
+ void show_list(struct cell *p)
37
+ {
38
+ if (p == NULL)
39
+ printf("\n");
40
+ else {
41
+ printf(" -> %.15g", p->data);
42
+ show_list(p->next);
43
+ }
44
+ }
45
+
46
+ void free_list(struct cell *q)
47
+ {
48
+ if (q->next != NULL)
49
+ free_list(q->next);
50
+ free(q);
51
+ }
52
+
53
+ int main(void)
54
+ {
55
+ double data;
56
+ struct cell *p = NULL;
57
+
58
+ while (1) {
59
+ printf("0以上のデータを入力して下さい(負の値で終了) -->");
60
+ if (scanf("%lf", &data) != 1 || data < 0) {
61
+ free_list(p);
62
+ break;
63
+ } else {
64
+ add_list(&p, data);
65
+ show_list(p);
66
+ }
67
+ }
68
+ return 0;
69
+ }
70
+ ```
71
+ このコードで分からないところはどこですか?