我一直在试图找出如何处理指针和结构。我写了下面的代码。

#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()的输出乱码?

爸爸名字:AAAA爸爸ID:11
妈妈的名字:BBBB妈妈的身份证:22
1孩子的名字:ïUï∞u u uh░├evhchildID:6846053
2孩子名称:ïUï∞u u uh░├evhchildID:6846053


如何定义长度不受限制的字符数组? (使用字符串也需要定义的长度)。

最佳答案

为什么print_child()的输出乱码?


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,但这不能保证。我建议初始化,以确保在创建Family类的对象时num_of_childs的初始值为0:

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

关于c++ - 找出指针和结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49571452/

10-11 16:31