使用new操作符的动态数组
c++: dynamic array using new operator
用户输入我必须在数组中收集的图书。你能帮我理解一下为什么当我进入第二本书的时候,第一本书被删除了吗?我全局定义了bookaux…
你能帮我理解为什么我不能收集
#define stop __asm nop
#include "book.h"
#include <iostream>
#include <cstdio>
using namespace std;
int counter = 0;
BOOK aux [1];
void print_catalogue()
{
}
void print_book(BOOK aBook)
{
cout << endl;
cout <<aBook.Autor<<", "<<aBook.Title<<", "<<aBook.Year<<", "<<aBook.PageCount<<", "<<aBook.Cost<<endl;
}
void new_book()
{
BOOK temp;
system("cls");
cin.getline (temp.Autor, 20);
cout <<"ENTERING NEW BOOK: " << endl <<endl;
cout <<"Input the author: ";
cin.getline (temp.Autor, 20);
cout <<"Input the title: ";
cin.getline (temp.Title, 50);
cout <<"Input the year of publishing: ";
cin >> temp.Year;
cout <<"Input the number of pages: ";
cin >> temp.PageCount;
cout <<"Input the cost: ";
cin >> temp.Cost;
cout << endl;
counter++;
BOOK * pn = new BOOK [counter];
if (counter > 0)
{
memcpy(pn, aux, counter * sizeof(BOOK));
}
pn[counter - 1] = temp;
BOOK * aux = new BOOK[counter];
memcpy(aux,pn, counter * sizeof(BOOK));
delete[] pn;
for (int i = 0; i < counter; i++)
{
print_book(aux[i]);
}
system("pause");
return;
}
void delete_books()
{
}
void write_catalogue()
{
}
void read_catalogue()
{
}
void menu()
{
char command;
do
{
system("cls");
cout << "p - Print the whole catalogue."<< endl;
cout << "n - Input a new book." << endl;
cout << "d - Delete existing book(s)." << endl;
cout << "w - Write the catalogue to a file." << endl;
cout << "r - Read the catalogue from a file." << endl;
cout << "Input a new command: ";
cin >> command;
cout << endl << endl;
switch (command)
{
case 'p': print_catalogue(); break;
case 'n': new_book(); break;
case 'd': delete_books(); break;
case 'w': write_catalogue(); break;
case 'r': read_catalogue(); break;
case 'q': return;
default :
{
cout << "Please, enter a correct command." << endl;
system("pause");
}
}
} while(true);
}
void main()
{
menu();
}
全局aux是指向一个BOOK - aux[0]的常量指针,不能再多了。你不能复制多于一本的书。重新定义一个局部变量,隐藏全局变量。你在函数new_book()返回后放的是" leak "
使用std::string和容器,不要滥用指针和全局变量
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 输出没有重复元素的动态数组(收缩数组)C++
- 正在插入动态数组
- 如何在动态数组上使用搜索函数
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 静态数组的自由动态数组
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- 为什么 c++ 动态数组的大小没有改变?
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 指针的 C++ 动态数组 - 何时需要使用它?
- 删除动态数组时未定义标识符
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 动态数组的 C++ 重载加运算符
- 基于数组的列表 - 动态数组创建时出错