简体   繁体   English

对char数组感到困惑

[英]Confused about char arrays

I am trying to implement the functions below, but printing out the output of Printme(), the program that freezes . 我正在尝试实现以下功能,但打印出Printme()的程序,该程序冻结了。 Any ideas why? 有什么想法吗?

int main() 
{
   for (int i=0; i<12; i++)
   {
        cout<< PrintMe()[i];
   }
   return 0;
}

char * PrintMe() {
  char str[12];
  strncpy (str, "hello world", 11);
  str[11] = 0;
  return str;
}

Your code invokes Undefined Behaviour as you are returning a pointer to a temporary. 您的代码在返回指向临时对象的指针时会调用未定义行为 As soon PrintMe ends its execution, str becomes destroyed. PrintMe一旦结束执行, str就会被销毁。 Thus the pointer your accessing with PrintMe()[i] is invalid. 因此,使用PrintMe()[i]访问的指针无效。

To fix this you have to return a heap allocated string (no automatic storage duration). 要解决此问题,您必须返回分配给堆的字符串(无自动存储持续时间)。 But dont forget to destroy it afterwards: 但是不要忘了以后销毁它:

char * PrintMe() {
  char* str = new char[12];
  strncpy (str, "hello world", 11);
  str[11] = 0;
  return str;
}

char* str = PrintMe();

for (int i=0; i<12; i++)
{
   cout<< str[i];
}

delete[] str;

Or as you're writing c++ nontheless, why dont you go with a std::string ? 还是在编写c ++时,为什么不使用std::string呢?

The program has undefined behaviour because function PrintMe returns a pointer to the first element of a local array that will be destroyed after exiting the function. 该程序具有未定义的行为,因为函数PrintMe返回一个指向本地数组第一个元素的指针,该指针在退出函数后将被破坏。 So the pointer will not be valid. 因此,该指针将无效。

Change the function the following way that to get the predicted result 按以下方式更改功能以获得预期结果

char * PrintMe() {
  static char str[12];
  strncpy (str, "hello world", 11);
  str[11] = 0;
  return str;
}

In your PrintMe function, you are returning a pointer to a local variable. 在您的PrintMe函数中,您将返回一个指向局部变量的指针。 This is undefined behavior: 这是未定义的行为:

char* PrintMe() {
    char str[12];
    //...
    return str;  // cannot do this, UB.
}

This works if you change the return type to std::string 如果将返回类型更改为std :: string,则此方法有效

std::string PrintMe() {
    char str[12];
    //...
    return str;  
}

The reason why the above now works is that a std::string is being constructed from the local array and returned instead of the local variable. 上面的方法现在起作用的原因是从本地数组构造了std :: string并返回了它,而不是返回了本地变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM