gpt4 book ai didi

c++ - const char * 在循环期间改变值

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

我有一个函数遍历 const char * 并使用该字符将对象添加到 std::map 的实例中,如果它是一系列识别字符。

#define CHARSEQ const char*

void compile(CHARSEQ s) throw (BFCompilationError)
{
std::cout << "@Receive call " << s << std::endl;

for(int i = 0; s[i] != '\0'; i++)
{
if (std::string("<>-+.,[]").find_first_of(s[i]) == std::string::npos)
{
throw BFCompilationError("Unknown operator",*s,i);
}
std::cout << "@Compiling: " << s[i] << std::endl;
std::cout << "@address s " << (void*)s << std::endl;
std::cout << "@var s " << s << std::endl;
controlstack.top().push_back(opmap[s[i]]);
}
}

传递的字符序列是"++++++++++."对于前三个迭代,打印语句显示 '+'、'+' 和 '+' 的预期值,并且 s 的值继续为“+++++++++++。”。然而,在第四次迭代中,s 变得困惑,产生了奇怪的值,例如 'Ð''öê''cR ''œk' 和许多其他字符序列。如果抛出异常的行被删除,并允许循环继续,则 s 的值不会再次改变。

其他函数可以访问s,但由于这不是一个多线程程序,所以我不明白为什么这很重要。我对为什么 s 发生变化并不感到困惑,但为什么它只在第四次迭代时发生变化。

我搜索过 SO,唯一看起来相关的帖子是 this one但它仍然没有回答我的问题。 (研究一直很困难,因为搜索“const char* 改变值”或类似的术语只会出现数百个 posts about what part of is is const)。

最后,我知道我可能应该使用 std::string,如果没有答案我会使用,但我仍然想了解这种行为。

编辑:

下面是调用这个函数的代码。

CHARSEQ text = load(s);

std::cout << "@Receive load " << text << std::endl;

try
{
compile(text);
}
catch(BFCompilationError& err)
{
std::cerr << "\nError in bf code: caught BFCompilationError @" << err.getIndex() << " in file " << s << ":\n";
std::cerr << text << '\n';
for(int i = 0; i < err.getIndex(); i++)
{
std::cerr << " ";
}
std::cerr << "^\n";
std::cerr << err.what() << err.getProblemChar() << std::endl;
return 1;
}

load 是:

CHARSEQ load(CHARSEQ fname)
{
std::ifstream infile (fname);
std::string data(""), line;
if (infile.is_open())
{
while(infile.good())
{
std::getline(infile,line);
std::cout << "@loading: "<< line << '\n';
data += line;
}
infile.close();
}
else
{
std::cerr << "Error: unable to open file: " << fname << std::endl;
}

return std::trim(data).c_str();
}

并且文件 fname++++++++++。 展开使得每行一个字符。

编辑 2:

这是控制台输出的示例:

@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: .
@Receive load ++++++++++.
@Receive call ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling:
@address s 0x7513e4
@var s ßu

Error in bf code: caught BFCompilationError @4 in file bf_src/Hello.txt:
ßu
^
Unknown operatorß

最佳答案

您的load 函数有缺陷。 c_str() 返回的 const char* 指针仅在底层 std::string 对象存在之前有效。但是dataload中的一个局部变量,return后被清除。它的缓冲区没有被零覆盖,而是保留为空闲内存。因此,返回后立即打印出值可能会起作用,但您的程序可能会在那里放置新值,并且您的指针指向的值将会改变。

我建议使用 std::string 作为 load 的返回值作为解决方法。

关于c++ - const char * 在循环期间改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14389518/

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