回答編集履歴

1

ソース追記

2019/04/19 14:07

投稿

cateye
cateye

スコア6851

test CHANGED
@@ -1 +1,145 @@
1
1
  気になった所:struct result *s_rt[NUM];の後の処理はループの中に入れましょう。また、free(s_rt);では、メモリの開放は出来ません。個別(free(s_rt[0]);)にしましょう。
2
+
3
+ 「追記」ほぼ完成してるようなので、参考までに。
4
+
5
+ ```c
6
+
7
+ #include <stdio.h>
8
+
9
+ #include <stdlib.h>
10
+
11
+ //
12
+
13
+ #define NUM 3
14
+
15
+ #define NUM1 20
16
+
17
+ //
18
+
19
+ struct result {
20
+
21
+ int number;
22
+
23
+ char name[NUM1];
24
+
25
+ int english;
26
+
27
+ };
28
+
29
+ //
30
+
31
+ int main(void)
32
+
33
+ {
34
+
35
+ struct result *s_rt[NUM];
36
+
37
+ for (int i = 0; i < NUM; i++) {
38
+
39
+ s_rt[i] = (struct result *)malloc(sizeof(struct result));
40
+
41
+ if (s_rt[i] == NULL) {
42
+
43
+ printf("メモリの動的確保に失敗しました\n");
44
+
45
+ if (i != 0) {
46
+
47
+ for (int j = 0; j < i; j++) {
48
+
49
+ free(s_rt[j]);
50
+
51
+ }
52
+
53
+ }
54
+
55
+ exit(1);
56
+
57
+ } else {
58
+
59
+ printf("%d番目の番号を入力してください:", i + 1);
60
+
61
+ scanf("%d", &s_rt[i]->number);
62
+
63
+ printf("%d番目の名前を入力してください:", i + 1);
64
+
65
+ scanf("%s", s_rt[i]->name);
66
+
67
+ printf("%d番目の英語の点数を入力してください:", i + 1);
68
+
69
+ scanf("%d", &s_rt[i]->english);
70
+
71
+ }
72
+
73
+ }
74
+
75
+ // int j;
76
+
77
+ for (int i = 0; i < NUM; i++) {
78
+
79
+ printf("番号:%d\n", s_rt[i]->number);
80
+
81
+ printf("名前:%s\n", s_rt[i]->name);
82
+
83
+ printf("英語の点数:%d\n", s_rt[i]->english);
84
+
85
+ free(s_rt[i]);
86
+
87
+ }
88
+
89
+ putchar('\n');
90
+
91
+
92
+
93
+ return 0;
94
+
95
+ }
96
+
97
+ ```
98
+
99
+ 結果
100
+
101
+ ```text
102
+
103
+ usr ~/Project/test/teratail % ./a.out
104
+
105
+ 1番目の番号を入力してください:2
106
+
107
+ 1番目の名前を入力してください:aaa
108
+
109
+ 1番目の英語の点数を入力してください:123
110
+
111
+ 2番目の番号を入力してください:4
112
+
113
+ 2番目の名前を入力してください:bbbbbbbb
114
+
115
+ 2番目の英語の点数を入力してください:456
116
+
117
+ 3番目の番号を入力してください:5
118
+
119
+ 3番目の名前を入力してください:dd
120
+
121
+ 3番目の英語の点数を入力してください:789
122
+
123
+ 番号:2
124
+
125
+ 名前:aaa
126
+
127
+ 英語の点数:123
128
+
129
+ 番号:4
130
+
131
+ 名前:bbbbbbbb
132
+
133
+ 英語の点数:456
134
+
135
+ 番号:5
136
+
137
+ 名前:dd
138
+
139
+ 英語の点数:789
140
+
141
+
142
+
143
+ usr ~/Project/test/teratail %
144
+
145
+ ```