gpt4 book ai didi

c++ - 创建动态字符串数组时出现段错误

转载 作者:行者123 更新时间:2023-11-28 07:39:35 26 4
gpt4 key购买 nike

我的 friend 正在编写一个基于文本的游戏,并让我查看这段崩溃的代码。我调试了它,它在创建动态数组时出现段错误。我不确定为什么,我建议他完全避免使用指针并使用 vector ,希望这能解决他的问题,但我很好奇这里到底出了什么问题。这是他的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

class nation
{
public:
void init();
string genName();
string getName();

private:
string myName;
int* myBorderPoints;
};

string nation::getName()
{
return myName;
}

string nation::genName()
{
int listLength = 0, listPos = 0, listRand = 0;
string nameToGen = "";
string* namePartList;
ifstream fileName;
fileName.open("NamePart1.txt");
listLength = fileName.tellg();
namePartList = new string[listLength]; // Seg fault here
while (fileName.good())
{
while (!fileName.eof())
{
getline(fileName,namePartList[listPos]);
listPos += 1;
}
}
listRand = rand() % listLength;
nameToGen += namePartList[listRand];
fileName.close();
listLength = 0;
listPos = 0;
listRand = 0;
nameToGen = "";
fileName.open("NamePart2.txt");
listLength = fileName.tellg();
namePartList = new string[listLength];
while (fileName.good())
{
while (!fileName.eof())
{
getline(fileName,namePartList[listPos]);
listPos += 1;
}
}
listRand = rand() % listLength;
nameToGen += namePartList[listRand];
fileName.close();
return nameToGen;
}

void nation::init()
{
srand(time(NULL));
myName = genName();
}

int main()
{
nation testNation;
testNation.init();
cout << testNation.getName();
return 0;
}

最佳答案

您正在调用 tellg:

listLength = fileName.tellg();

在没有读取任何内容的情况下,这取决于文件是否成功打开将返回 0-1 因此您将调用它:

namePartList = new string[listLength]

可能有一个不受欢迎的值(value)。我很确定自 allocating a zero sized 以来它正在返回 -1应该可以。

这也适用于稍后的代码,使用 std::vector 可能更有意义。

关于c++ - 创建动态字符串数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115807/

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