c/c++语言开发共享返回的字符串值变为垃圾

我试图将字符array值传递给字符pointer 。 然后将此值返回给正在调用它的方法,但在返回之后,该值将变为垃圾。 谁能帮我?

 #include  const char * getname(){ char nam[10]; char * name; gets(nam); name = nam; return name; } main(){ printf("%s",getname()); getch(); } 

一切都很好,直到字符串返回

    nam范围是函数getname()的本地,你通过name指针返回nam地址

     const char * getname(){ char nam[10]; : name = nam; return name; } 

    nam;分配内存nam; 动态。 喜欢:

     nam = malloc(sizeof(char)*10); 

    另外可能有bufferoverun不使用gets() ,喜欢:

     nam = malloc(sizeof(char)*10); fgets( nam, 10, stdin ); 

    你也不需要使用name一个额外的变量简单的return nam是好的。

     const char * getname(){ char * nam = malloc(sizeof(char)*10); fgets( nam, 10, stdin ); return nam; } 

    nam变量具有函数范围。 这意味着一旦函数结束,就释放该变量的内存。 因此,指向您返回的内存的指针将不再有效。

    你可以传入指针:(在这种情况下有点无意义,你可以看到)

     void getname(char *name) { gets(name); } 

    你可以malloc (坏,因为那时你需要在某个时候再次free它):

     const char * getname(){ char * name = malloc(10); gets(name); return name; } 

    您的问题是return name返回堆栈变量的地址,该变量在函数返回后超出范围。

    有几种方法可以解决这个问题(至少)。

    第一种是在函数外部分配地址然后传入:

     char *getname (char *buff) { strcpy (buff, "pax"); return buff; } char name[20]; printf ("Name is '%s'n", getname (name)); 

    第二种是使用在函数退出时没有超出范围的分配函数(指针可能但是,只要你传回它们,你仍然可以到达分配的内存):

     char *getname (void) { char *buff = malloc (21); // should really check this for failure. strcpy (buff, "pax"); return buff; } buff = getname(); printf ("Name is '%s'n", buff); free (buff); // This is important, caller is responsible // for freeing the memory. 

    声明nam static也可以:

     const char * getname() { static char nam[10]; ... 

    注意:此代码不是线程安全的,因为现在将nam视为全局声明。

    需要了解更多c/c++开发分享返回的字符串值变为垃圾,也可以关注C/ C++技术分享栏目—计算机技术网(www.ctvol.com)!

      以上就是c/c++开发分享返回的字符串值变为垃圾相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/980596.html

      (0)
      上一篇 2021年12月14日
      下一篇 2021年12月14日

      精彩推荐