指针数组函数参数-奇怪的行为
array of pointers function parameter - odd behaviour
我正在调试一个程序,但不太了解发生了什么。根据用户输入填充图书数组后,我尝试按字母顺序(按书名)排列指向图书对象的指针数组。运行该程序会导致seg错误,调试器向我显示,当调用我的orderAlphabetly函数时,指针数组(在此之前非常好)只包含三个元素。有什么想法吗?
谢谢!
#include <iostream>
#define MAXBKS 20
using namespace std;
typedef struct book{
float price;
string name;
string author;
}book;
// addBooks(): Gather user input and add book structs to array.
// @Params: the main library array, and its size.
//
void addBooks(book library[], int size){
string name, author, price;
for(int i = 0; i< size; ++i){
cout<< "Enter the name of the book, author, and price, each separated by "~": ";
if (cin.peek() == 'n') break;
getline(cin, name, '~');
getline(cin, author, '~');
getline(cin, price, '~');
library[i].name = name;
library[i].author = name;
library[i].price = stod(price);
cin.get();
}
}
// orderAlphabetically(): assign pointers to alphabetically ordered book
// titles.
// @Params: the main library array, and the pointer array to hold the order
//
void orderAlphabetically(book *library_ptrs[], int size){
int pos;
book *temp;
for (int i = size; i > 1; i--){
pos = 0;
for (int j = 0; j < i; ++j){
if ((library_ptrs[i]->name).compare(library_ptrs[pos]->name) > 0 )
pos = j;
}
temp = library_ptrs[pos];
library_ptrs[pos] = library_ptrs[i-1];
library_ptrs[i-1] = temp;
}
}
void printLibrary(book library[], int size){
int i = 0;
while ((library[i].price != 0) && (i < size)){
cout<< "nBook "<< i+1<< ": "<< endl;
cout<< library[i].name<< endl;
cout<< library[i].author<< endl;
cout<< library[i].price<< endl;
cout<<endl;
++i;
}
}
int main(){
book library[MAXBKS] = {0};
book *library_ptrs[MAXBKS] = {0};
// Add books to the library until the user enters 'enter'
addBooks(library, MAXBKS);
// Print entered books
cout<< "nThese are the books you have added: "<< endl;
printLibrary(library, MAXBKS);
// Order Alphabetically
for (int i = 0; i < MAXBKS; ++i)
library_ptrs[i] = library + i;
orderAlphabetically(library_ptrs, MAXBKS);
return 0;
}
编辑:已修复循环
while ((library[i].price != 0) && (i < size)) // i <= size is wrong
if ((library_ptrs[i]->name).compare(library_ptrs[pos]->name) > 0) // i was initialized to size, so similar problem, out of bound.
请查看std::sort(),而不是滚动自己的排序函数。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值