C++双指针输出

C++ double pointer output

本文关键字:输出 指针 C++      更新时间:2023-10-16

C++noob有一个问题,为什么我的代码以一种方式工作,而不是以另一种方式。。我有一个带构造函数的book类,它接受一个int参数并将其设置为页数(即书中的页数)。我还有一个主.cpp.

book.h:

#ifndef BOOK_H
#define BOOK_H
#include <iostream>
#include <string>
using namespace std;
class Book{
  public:
    Book(int);
    int pages;
};
#endif

Book.cpp:

#include <iostream>
#include <string>
using namespace std;
#include "Book.h"
Book::Book(int t){
  pages = t;
}

main.cpp:

#include <iostream>
#include <string>
using namespace std;
 #include "Book.h"
Book** elements;
int size = 0;
int add(Book* b);
int main()
{
  Book* b1 = new Book(99);
  Book* b2 = new Book(100);
  Book* b3 = new Book(101);
  Book* b4 = new Book(102);
  add (b1);
  add (b2);
  add (b3);
  add (b4);
 //***I get garbage values printed here***
  cout << " pages " << elements[0]->pages << "n";
  cout << " pages " << elements[1]->pages << "n";
  cout << " pages " << elements[2]->pages << "n";
  cout << " pages " << elements[3]->pages << "n";
  //delete the books
  delete b1;
  delete b2;
  delete b3;
  delete b4;
  return 0;
}
int add(Book* b)
{
  Book* newList[size+1];
  for(int i = 0; i < size; i++)
  {
     newList[i] = elements[i];
  }
  delete elements;
  newList[size] =  b;
  elements = newList;
  //***i get correct values printed here ***
  cout << " pages in function: " << elements[size]->pages << "n";
  size++;
  return 1;
}

我的问题是,为什么当我在函数"add"中打印页面时,页面可以打印,但当我在外部打印时,却得到了垃圾值。

我的输出如下:
pages in function: 99 pages in function: 100 pages in function: 101 pages in function: 102 pages 2293484 pages 4667584 pages 4667584 pages 4667584

其中as输出应为:
pages in function: 99 pages in function: 100 pages in function: 101 pages in function: 102 pages 99 pages 100 pages 101 pages 102

newlist[i] = elements[i]仅将elements[i]处的指针分配给newlist[i]。稍后,您调用了deleteelements[i](也由newlist[i])指向的对象不见了。所以你得到了函数之外的随机值。

一个大问题是newList是一个本地数组,因此一旦add退出,它就会被销毁。

由于addelements更改为指向newList,这意味着elements在调用add之后总是指向垃圾。

(如果这不是一次使用指针的深思熟虑的练习,那么你真的应该使用标准的数据结构,比如std::vector,它的主要用途是成为一个可调整大小的数组)