编程练习
3.下面是一个结构声明:
struct chaff
{
char dross[20];
int slag;
};
编写一个程序,使用定位new运算符将一个包含两个这种结构的数组放在一个缓冲区中。然后,给结构的成员赋值(对于char数组,使用函数strcpy()),并使用一个循环来显示内容。一种方法是像程序清单9.10那样将一个静态数组用作缓冲区;另一种方法是使用常规new运算符来分配缓冲区。
//循环显示函数使用指针作为形参传递
#include<iostream>
#include<new>
#include<cctype>
using namespace std;
const int Arsize = 50;
struct chaff
{
char dross[20];
int slag;
};
char buffer[Arsize];
void display(chaff *m_ch,int n);
int main()
{
chaff *p1;
p1 = new (buffer) chaff[2]; //使用定位new运算符 从字符数组buffer中分配内存
//给一个包含2个元素的chaff结构
cout << "给结构成员赋值:" << endl;
char name[Arsize];
for (int i = 0; i < 2; i++)
{
cout << "Enter the dross: ";
cin.getline(name, Arsize);
strcpy_s(p1[i].dross, name);
cout <<"Enter the slag: ";
cin >> p1[i].slag;
cin.get(); //数字与字符串混合输入时 应在数字输入后加上cin.get()
//来消除数字输入后换行符的影响
}
display(p1,2);
system("pause");
return 0;
}
void display(chaff *m_ch,int n)
{
for (int i = 0; i < n; i++)
{
cout << "The deoss is:" << m_ch[i].dross << endl;
cout << "The slag is:" << m_ch[i].slag << endl;
}
}
//循环显示函数使用引用方式传递形参
#include<iostream>
#include<new>
#include<cctype>
using namespace std;
const int Arsize = 50;
struct chaff
{
char dross[20];
int slag;
};
char buffer[Arsize];
void display(chaff &m_ch,int n);
int main()
{
chaff *p1;
p1 = new (buffer) chaff[2];
cout << "给结构成员赋值:" << endl;
char name[Arsize];
for (int i = 0; i < 2; i++)
{
cout << "Enter the dross: ";
cin.getline(name, Arsize);
strcpy_s(p1[i].dross, name);
cout <<"Enter the slag: ";
cin >> p1[i].slag;
cin.get();
}
display(*p1,2);
system("pause");
return 0;
}
void display(chaff &m_ch,int n)
{
//chaff* p2 = &m_ch;
for (int i = 0; i < n; i++)
{
cout << "The deoss is:" << (&m_ch)[i].dross << endl;
cout << "The slag is:" << (&m_ch)[i].slag << endl;
//cout << "The deoss is:" << p2[i].dross << endl;
//cout << "The slag is:" << p2[i].slag << endl;
}
}
总结:
1、当数字与字符串混合输入时 应在数字输入后加上cin.get()来消除数字输入后换行符的影响
2、对于函数参数的选取,如果数据对象为结构,则使用指针或引用作为形参传递
如上述情况,结构对象为数组时,使用指针传递更好一些。
3、无论对于第一种中的 m_ch[i].dross 还是第二种中的 (&m_ch)[i].dross 、p2[i].dross
m_ch、(&m_ch)、p2 属性都为地址或指针。