figure out pointers and structs
我一直在想如何处理指针和结构。我写了以下代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | #include <iostream> using namespace std; struct Person { char name[20]; //Question 2 int id; }; const int max_num_of_childs=10; struct Family { Person dad; Person mom; int num_of_childs; Person* child[max_num_of_childs]; }; void add_child (Family& f) { char answer; do { if (f.num_of_childs==max_num_of_childs) { cout <<"no more children" <<endl; return; } cout <<"more child? Y/N" <<endl; cin >> answer; if (answer == 'Y') { f.child[f.num_of_childs] = new Person; cout <<"enter name and id" << endl; cin >> f.child[f.num_of_childs]->name; cin >> f.child[f.num_of_childs]->id; f.num_of_childs++; } } while (answer=='Y'); return; } void add (Family& f) { cout <<"insert dad name & id" << endl; cin >> f.dad.name >> f.dad.id; cout <<" insert mom name & id" << endl; cin >> f.mom.name >> f.mom.id; add_child (f); } void print_child (const Family f) //Question 1 { for (int i=0; i<f.num_of_childs; i++) cout <<"#" << i+1 <<"child name:" << f.child[f.num_of_childs]->name <<"child id:" << f.child[f.num_of_childs]->id << endl; } void print (const Family f) { cout <<"dad name:" << f.dad.name <<"\tdad id:" << f.dad.id << endl; cout <<"mom name:" << f.mom.name <<"\tmom id:" << f.mom.id << endl; print_child (f); } int main() { Family f; f.num_of_childs=0; add(f); print(f); return 0; } |
为什么
1 2 3 4 | dad name: AAAA dad id: 11 mom name: BBBB mom id: 22 1child name: ? U?∞ u u u h?├evhchild id: 6846053 2child name: ? U?∞ u u u h?├evhchild id: 6846053 |
号
如何定义长度不受限制的字符数组?(使用字符串还需要定义的长度)。
Why is the output of
print_child() gibberish?
号
在
1 2 3 4 5 | void print_child (const Family f) //Question 1 { for (int i=0; i<f.num_of_childs; i++) cout <<"#" << i+1 <<"child name:" << f.child[f.num_of_childs]->name <<"child id:" << f.child[f.num_of_childs]->id << endl; } |
我认为应该有:
1 2 3 4 5 | void print_child (const Family f) //Question 1 { for (int i=0; i<f.num_of_childs; i++) cout <<"#" << i+1 <<"child name:" << f.child[i]->name <<"child id:" << f.child[i]->id << endl; } |
号
除此之外还有一件小事。
通常整数类成员初始化为0,但这是不保证的。我建议初始化,以确保在创建家族类对象时,
1 2 3 4 5 6 7 | struct Family { Person dad; Person mom; int num_of_childs = 0; Person* child[max_num_of_childs]; }; |