将指针数组传递给函数
Passing pointer array to function
我有以下情况。下面的程序虽然在我运行时编译得很好,但它停止了工作。有人能帮我找出问题吗?我想我在函数中使用了错误的指针,但我不知道如何修复它并使其在中工作
#include <fstream>
//some other includes
using namespace std;
struct Book{
string id;
string title;
string authorName;
string authorSurname;
};
int load(Book* booksInfo)
{
int count = 0;
ifstream fin;
fin.open("myfile.txt");
if (!fin.is_open())
{
cout << "Unable to open myfile.txt filen";
exit(1);
}
while (fin.good())
{
getline(fin, booksInfo[count].id, '#');
getline(fin, booksInfo[count].title, '#');
getline(fin, booksInfo[count].authorName, '#');
getline(fin, booksInfo[count].authorSurname, '#');
count++;
} //end while
fin.close();
return 0;
} //end load()
//some other functions here
int main()
{
Book * bookInfo;
bookInfo = (Book*) malloc(sizeof(Book)*100);
//some code here
load(bookInfo);
//some code here
return 0;
} //end main
使用std::vector
存储您的图书列表:
#include <fstream>
#include <vector>
//some other includes
using namespace std;
struct Book{
string id;
string title;
string authorName;
string authorSurname;
};
vector<Book> load()
{
ifstream fin;
Book book;
vector<Book> books;
fin.open("myfile.txt");
if (!fin.is_open())
{
cout << "Unable to open myfile.txt filen";
return books;
}
while (fin.good())
{
getline(fin, book.id, '#');
getline(fin, book.title, '#');
getline(fin, book.authorName, '#');
getline(fin, book.authorSurname, '#');
books.push_back(book);
} //end while
fin.close();
return books;
} //end load()
//some other functions here
int main()
{
vector<Book> books = load();
return 0;
} //end main
使用malloc
来分配非POD类型是UB,在您的案例中,由于没有调用std::string
构造函数,因此book实例将在字符串中包含一些垃圾。它不仅仅是垃圾字符串,它很可能是指向一些随机位置的垃圾指针
如果确实需要手动分配内存,则应该使用std::vector
或至少使用new
,以便在堆中创建新的Book
实例
如果你真的,真的必须使用malloc
,你可以使用放置new
在你以某种方式分配的原始内存中创建有效的std::string
(在你的情况下是malloc
)。
您需要使用
Book* bookInfo = new Book[100];
相反。这是因为,在C++中,struct
是一个对象(就像class
一样),对普通旧数据以外的任何对象调用malloc都是未定义的行为。
记住使用delete[] bookInfo;
来释放内存(注意方括号)。如果单独使用delete
,则会出现更多未定义的行为。
还要确保你的阅读量不超过100行;否则您将溢出数组:还有更多未定义的行为。
最后,考虑使用像std::vector
这样的标准模板库容器。
关于:
Book bookInfo[100];
这完全避免了堆分配,应该可以达到您的目的。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针