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

回答編集履歴

2

C++コード修正

2020/01/31 03:14

投稿

shiracamus
shiracamus

スコア5406

answer CHANGED
@@ -58,7 +58,7 @@
58
58
 
59
59
  struct StaffList {
60
60
  int num = 0;
61
- struct Staff *staff = NULL;
61
+ Staff *staff = NULL;
62
62
 
63
63
  void add(const char *name) {
64
64
  staff = (Staff *)reallocarray(staff, sizeof(Staff), num + 1);
@@ -70,7 +70,7 @@
70
70
  int main(void) {
71
71
  printf("start\n");
72
72
 
73
- struct StaffList stafflist;
73
+ StaffList stafflist;
74
74
  stafflist.add("akai");
75
75
  stafflist.add("aoi");
76
76
  stafflist.add("hogehoge");

1

C++の例を追記

2020/01/31 03:14

投稿

shiracamus
shiracamus

スコア5406

answer CHANGED
@@ -43,4 +43,44 @@
43
43
  stafflist->num = num;
44
44
  stafflist->staff = staff;
45
45
  }
46
+ ```
47
+
48
+ ちょっと脱線しますが、C++だとこんな書き方ができます。
49
+
50
+ ```c++
51
+ #include <stdio.h>
52
+ #include <stdlib.h>
53
+ #include <string.h>
54
+
55
+ struct Staff {
56
+ char name[64];
57
+ };
58
+
59
+ struct StaffList {
60
+ int num = 0;
61
+ struct Staff *staff = NULL;
62
+
63
+ void add(const char *name) {
64
+ staff = (Staff *)reallocarray(staff, sizeof(Staff), num + 1);
65
+ strncpy(staff[num].name, name, sizeof(staff[num].name) - 1);
66
+ num++;
67
+ }
68
+ };
69
+
70
+ int main(void) {
71
+ printf("start\n");
72
+
73
+ struct StaffList stafflist;
74
+ stafflist.add("akai");
75
+ stafflist.add("aoi");
76
+ stafflist.add("hogehoge");
77
+
78
+ printf("result\n");
79
+ for(int i = 0; i < stafflist.num; i++) {
80
+ printf("No %d, %s\n", i+1, stafflist.staff[i].name);
81
+ }
82
+
83
+ printf("end\n");
84
+ return 0;
85
+ }
46
86
  ```