C++ 常量字符*在循环期间更改值

C++ 常量字符*在循环期间更改值,c++,pointers,c-strings,const-char,C++,Pointers,C Strings,Const Char,我有一个函数,它遍历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

我有一个函数,它遍历
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]]);
     }
 }
其中
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();

您的
load
功能有缺陷。由
c_str()
返回的
const char*
指针仅在底层
std::string
对象存在之前有效。但是
data
load
中的一个局部变量,返回后被清除。它的缓冲区不会被零覆盖,而是保留为可用内存。因此,在返回后立即打印出值可能会起作用,但您的程序可能会在其中放入新值,指针指向的值将发生变化


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

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


我建议使用
std::string
作为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();
@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ß