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

回答編集履歴

1

ソース追記

2019/04/19 14:07

投稿

cateye
cateye

スコア6851

answer CHANGED
@@ -1,1 +1,73 @@
1
- 気になった所:struct result *s_rt[NUM];の後の処理はループの中に入れましょう。また、free(s_rt);では、メモリの開放は出来ません。個別(free(s_rt[0]);)にしましょう。
1
+ 気になった所:struct result *s_rt[NUM];の後の処理はループの中に入れましょう。また、free(s_rt);では、メモリの開放は出来ません。個別(free(s_rt[0]);)にしましょう。
2
+ 「追記」ほぼ完成してるようなので、参考までに。
3
+ ```c
4
+ #include <stdio.h>
5
+ #include <stdlib.h>
6
+ //
7
+ #define NUM 3
8
+ #define NUM1 20
9
+ //
10
+ struct result {
11
+ int number;
12
+ char name[NUM1];
13
+ int english;
14
+ };
15
+ //
16
+ int main(void)
17
+ {
18
+ struct result *s_rt[NUM];
19
+ for (int i = 0; i < NUM; i++) {
20
+ s_rt[i] = (struct result *)malloc(sizeof(struct result));
21
+ if (s_rt[i] == NULL) {
22
+ printf("メモリの動的確保に失敗しました\n");
23
+ if (i != 0) {
24
+ for (int j = 0; j < i; j++) {
25
+ free(s_rt[j]);
26
+ }
27
+ }
28
+ exit(1);
29
+ } else {
30
+ printf("%d番目の番号を入力してください:", i + 1);
31
+ scanf("%d", &s_rt[i]->number);
32
+ printf("%d番目の名前を入力してください:", i + 1);
33
+ scanf("%s", s_rt[i]->name);
34
+ printf("%d番目の英語の点数を入力してください:", i + 1);
35
+ scanf("%d", &s_rt[i]->english);
36
+ }
37
+ }
38
+ // int j;
39
+ for (int i = 0; i < NUM; i++) {
40
+ printf("番号:%d\n", s_rt[i]->number);
41
+ printf("名前:%s\n", s_rt[i]->name);
42
+ printf("英語の点数:%d\n", s_rt[i]->english);
43
+ free(s_rt[i]);
44
+ }
45
+ putchar('\n');
46
+
47
+ return 0;
48
+ }
49
+ ```
50
+ 結果
51
+ ```text
52
+ usr ~/Project/test/teratail % ./a.out
53
+ 1番目の番号を入力してください:2
54
+ 1番目の名前を入力してください:aaa
55
+ 1番目の英語の点数を入力してください:123
56
+ 2番目の番号を入力してください:4
57
+ 2番目の名前を入力してください:bbbbbbbb
58
+ 2番目の英語の点数を入力してください:456
59
+ 3番目の番号を入力してください:5
60
+ 3番目の名前を入力してください:dd
61
+ 3番目の英語の点数を入力してください:789
62
+ 番号:2
63
+ 名前:aaa
64
+ 英語の点数:123
65
+ 番号:4
66
+ 名前:bbbbbbbb
67
+ 英語の点数:456
68
+ 番号:5
69
+ 名前:dd
70
+ 英語の点数:789
71
+
72
+ usr ~/Project/test/teratail %
73
+ ```