从函数返回本地字符数组

Sij*_*ith 1 c c++ string pointers visual-c++

如何从一个函数返回本地字符数组

char* testfunction()
{
char array[] = "Hello World";
 return array;
}

char main()
{
 char* array = testfunction();
 printf(" %s -> string", array);
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

这些代码会导致未知错误

@ $ @ < Ʉ؅ ; Y@ - >字符串

bil*_*llz 7

当main()中的testfunction()返回array变为悬空指针时,您将返回指向局部变量的指针.

使用std::string替代

#include <string>
#include <iostream>

std::string testfunction()
{
    std::string str("Hello World");
    return str;
}

int main()
{
    std::cout << testfunction() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


HAL*_*HAL 5

您不应该直接返回堆栈变量的地址,因为一旦删除堆栈帧(在函数返回后)它就会被销毁.

你可以做到这一点.

#include <stdio.h>
#include <algorithm>

char* testfunction()
{
   char *array = new char[32];
   std::fill(array, array + 32, 0); 
   snprintf(array, 32, "Hello World");
   return array;
}

int main()
{
   char* array = testfunction();
   printf(" %s -> string", array);
   delete[] array;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)