Return local character array from a function [duplicate]

感情迁移 提交于 2020-01-24 20:13:25

问题


How to return a local character array from one function

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

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

THis code results unknown error

�@$�@<��Ʉ؅�;���Y@��� -> string


回答1:


You should not return the address of the stack variable directly as it is destroyed once the stack frame is removed(after the function returns).

You could do this.

#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;
}



回答2:


You are returning a pointer which points to a local variable, when testfunction() returns array in main() becomes dangling pointer.

use std::string instead

#include <string>
#include <iostream>

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

int main()
{
    std::cout << testfunction() << std::endl;
    return 0;
}



回答3:


Perhaps, this is what you want:

const char *testfunction(void)
{
        return "Hello World";
}



回答4:


You can't return the address of a local variable. (if you use gcc you should get some warnings)

You can try to use the keyword static instead:

char    *test()
{
  static char array[] = "hello world";
  return (array);
}


来源:https://stackoverflow.com/questions/18444271/return-local-character-array-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!