返回的字符串值变成垃圾 [英] Returned string value becomes garbage

查看:29
本文介绍了返回的字符串值变成垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将字符 array 值传递给字符 pointer.然后这个值被返回给调用它的方法,但是在它被返回之后,这个值就变成了垃圾.谁能帮帮我?

Im trying to pass a character array value to a character pointer. then this value gets returned to a method that is calling it, but after it gets returned, the value becomes garbage. can anyone help me?

#include <stdio.h>

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

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

everything is fine, until the string gets returned

推荐答案

nam的作用域是getname()函数的局部,你通过nam地址>名称指针

Scope of nam is local to function getname(), you are returning nam address through name pointer

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

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

allocate memory for nam; dynamically. like:

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

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

additionally there may be bufferoverun don't use gets(), do like:

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

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

You also not need to use name an extra variable simple return nam is good.

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

这篇关于返回的字符串值变成垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆