vendredi 30 mars 2018

figure out pointers and structs

While I've been trying to figure out how to deal with pointers&structs, I wrote the following code.

  1. Why does the output of function print_child is gibberish? OUTPUT:

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

  1. How can I define an array of chars with unlimited length? (Using string also requires a defined length)

    #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 << "\ninsert 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;
    }
    
    

Aucun commentaire:

Enregistrer un commentaire