这个char *为什么以及何时改变值

Why and when does this char * change values?

本文关键字:何时 改变 char 为什么 这个      更新时间:2023-10-16

观察下面的代码。我从std::string到C风格字符串再回到std::string的原因是因为bmd2create是C绑定API的一部分,它必须采用C风格字符串。否则,我将尽可能使用std::string

OtherFile.h

void bmd2create(const char * filename) {
  std::string sFileName (filename);
  // do things with sFileName
  std::ostringstream ostr;
  ostr << "t(in)  filename       = " << filename << "n";
  logger.log(Logger::LogLevel::LOG_DEBUG, ostr.str());
}

Main.cpp

const char * filename = std::string(filepath + "dataset1.out").c_str();
// *filename is 46 '.'
bmd2create(filename);
// *filename is now 0 ''

文件名指针被移动的位置和原因?把它移回到弦的开始的最好方法是什么?

这一行特别没用:

const char * filename = std::string(filepath + "dataset1.out").c_str();

创建一个临时的std::string,然后用c_str()获得一个指向其内容的指针。临时变量在完整表达式的末尾,在下一行执行之前被清理。在这一点上,指针没有移动。使用它是未定义的行为。

在调用bmd2create之前你认为指针是ok的原因是指向的内存还没有被覆盖。但它不再为字符串所有,因此任何将来的分配都可以用新对象替换它。

正确的代码应该是:

std::string filename = std::string(filepath) + "dataset1.out";
bmd2create(filename.c_str());