找出指针和结构
figure out pointers and structs
我一直在尝试弄清楚如何处理指针&结构。我写了以下代码。
#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];
};
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- C++:映射结构中的结构指针
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 类的静态结构指针声明在C++
- 在两个.cpp文件之间定义全局类/结构指针
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何在地图中使用结构指针
- 结构指针在"新"调用上给出已分配的地址?
- 铸造结构指针指向C 的工会指针
- c++ 结构指针在初始化为 NULL 时无法读取内存
- 函数中的结构指针的地址为0x1
- C 用结构指针初始化结构
- C 结构指针铸成数组Interop C#
- 方法中不允许访问结构指针
- 如何打印出结构指针
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 尝试将结构指针传递给类时出错
- 初始化结构指针的值
- 使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?