找出指针和结构

figure out pointers and structs

本文关键字:结构 指针      更新时间:2023-10-16

我一直在尝试弄清楚如何处理指针&结构。我写了以下代码。

#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;
}

为什么print_child() gibberish的输出?

爸爸名:AAAA爸爸ID:11妈妈名:BBBB妈妈ID:221个子名称:•Uï∞U U U U uh░├evhchildID:68460532个孩子的名称:•Uï∞U U U U Uh░├evhchildID:6846053

如何定义一个无限长度的字符阵列?(使用字符串还需要定义的长度(。

为什么print_child() Gibberish的输出?

print_child()方法中,代码从f.child数组的初始化范围内达到。有:

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_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;
}

i总是比f.num_of_childs要小,因此代码不会到达非初始化的内存。

除此之外,还有一件小事。

通常,整数类成员会初始化为0,但不能保证。我建议初始化,以确保创建家庭类的对象时,num_of_childs的初始值为0:

struct Family
{
    Person dad;
    Person mom;
    int num_of_childs = 0;
    Person* child[max_num_of_childs];
};