gpt4 book ai didi

将指针传递给函数时 C++ 崩溃

转载 作者:行者123 更新时间:2023-11-30 01:15:30 24 4
gpt4 key购买 nike

我想做的是显示指向对象数组的指针。这是我的主程序,它崩溃的函数是 listAll()。如果我只输入一个对象,它就可以工作,但是当我输入第二个对象时,它就会崩溃。我不知道出了什么问题。选择 menuOption 1 两次然后尝试调用 list all 后出现问题。我看到数组大小没有增加..

#include <fstream> 
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

#include "fileStuff.h"

bool menu();
bool menuOptions(int option);
void fileIO();
void listAll(interact * obs, int arryO);

int main()
{

bool isRunning = true;
while (isRunning)
{
isRunning = menu();
}
return 0;
}

bool menu()
{
int option = 0;
cout << "1: add new backpack. " << endl
<< "2: delete a backpack "<< endl
<< "3: sort ascending by id " << endl
<< "4: sort descending by id " << endl
<< "5: list all backpacks " << endl
<< "6: quit" << endl;
cin >> option;
return menuOptions(option);
}

bool menuOptions(int option)
{

static int arrayO = 0;
static interact *obs = new interact[arrayO];
fileStuff test;
int tempBagId = 0, tempInvSpaces = 0, tempAmtOfItemsInInv = 0;
double tempInvMaxWeight = 0.0;
string tempBagType, tempBagCondish;
int t = 0 ;
int i = 0;
switch (option)
{
case 1:
cout << "bagId? ";
cin >> tempBagId;
cout << "How many inv spaces? ";
cin >> tempInvSpaces;
cout << "How much weight can the bag hold? ";
cin >> tempInvMaxWeight;
(obs + arrayO)->setBagId(tempBagId);
(obs + arrayO)->setInvSpaces(tempInvSpaces);
(obs + arrayO)->setInvMaxWeight(tempInvMaxWeight);
cout << "all stored" << endl;
arrayO++;
break;
case 2:
//listmanager delete one

//arrayO--;
break;
case 3:
//sort ascending by id
break;
case 4:
//sort descending by id
break;
case 5:
//list all
listAll(obs, arrayO);
break;

case 6:
obs = NULL;
delete obs;
return false;
break;
default:
break;
}
}


void listAll(interact * obs, int arryO)
{
int i = 0;
cout << i << endl;
cout << arryO << endl;

}

下面是我类(class)的要点。

#include "listManager.h"
#include <iostream>
#include <string>
using namespace std;

interact::interact()
{
bagId = 0;
invSpaces = 0;
invMaxWeigt = 0;

}

void interact::setBagId(int id)
{
bagId = id;
}
void interact::setInvSpaces(int spaces)
{
invSpaces = spaces;
}

void interact::setInvMaxWeight(double weight)
{
invMaxWeigt = weight;
}

int interact::getBagId()
{
return bagId;
}
int interact::getInvSpaces()
{
return invSpaces;
}

double interact::getInvMaxWeight()
{
return invMaxWeigt;
}

最佳答案

你有:

static int arrayO = 0;
static interact *obs = new interact[arrayO];

这将创建一个长度为 0 的动态数组。正如 Ben 所说,指针永远不会改变。

崩溃可能是由于在增加索引(arrayO++;)后尝试访问它造成的,之后它将只是访问越界内存。

关于将指针传递给函数时 C++ 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com