我正在尝试制作一个名称生成器,它使用从三个不同数组访问的预设音节。
#include "main.hpp"
Namegen::Namegen() {
}
const char *Namegen::getFirst() {
const char *name;
int rNum = rng->getInt(0, 5);
const char *firstSyllable = start[rNum];
rNum = rng->getInt(0, 5);
const char *secondSyllable = mid[rNum];
rNum = rng->getInt(0, 5);
const char *lastSyllable = end[rNum];
name = firstSyllable + *secondSyllable + *lastSyllable;
return name;
}
每个数组中共有 6 个音节,所以我将最小值设置为 0,将最大值设置为 5。总共六个数字。然而,出于某种原因,它看起来像是在某处生成 8?我不完全确定异常在说什么,但希望其他人知道。这是一个异常(exception)(即使它已经在标题中):
0xC0000005: Access violation reading location 0x0000000000000008.
这是我的 Namegen.hpp 文件(通过 main.hpp 文件链接):
#pragma once
class Namegen {
public:
const char *start[6] = { "Ba", "Ce", "Ti", "Mo", "Lu", "Dy" };
const char *mid[6] = { "ma", "te", "di", "so", "ku", "ly" };
const char *end[6] = { "ban", "can", "dan", "fan", "gan", "han" };
Namegen();
TCODRandom *rng;
const char *getFirst();
};
为什么会抛出这个异常,我该如何解决?
我已经到了可以使用以下代码成功连接值的地步:
std::string Namegen::getName() {
int r = rng->getInt(0, 2);
std::string firstSyll = fSyll[r];
r = rng->getInt(0, 2);
std::string midSyll = mSyll[r];
r = rng->getInt(0, 2);
std::string lastSyll = lSyll[r];
std::string name = std::string(firstSyll) + std::string(midSyll) + std::string(lastSyll);
return name;
}
但是,它现在抛出这个异常:
Exception thrown at 0x00007FF978AD9E7A (ucrtbased.dll) in AotDK.exe: 0xC0000005: Access violation reading location 0x0000000000000000.
最佳答案
name = firstSyllable + *secondSyllable + *lastSyllable;
远不是串联。 (编译器会编译它,因为它认为您正在对 firstSyllable
进行一些指针运算。)行为实际上是未定义的,因为您分配的不是 nullptr
的东西。或对象的地址 name
.
放弃所有char*
东西,然后使用 std::string
反而。那么+
将充当连接,因为它是字符串类中的重载运算符。
您的数据将采用以下形式
std::vector<std::string> start = { "Ba", "Ce", "Ti", "Mo", "Lu", "Dy" };
它展示了 C++ 标准库的强大功能。你需要 #include <string>
和 #include <vector>
引入该功能。
关于c++ - 0xC0000005 : Access violation reading location 0x0000000000000008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755011/