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

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

问题描述

我试着去一个字符阵列值传递给一个字符指针。那么这个值获取返还到调用它的方法,但它得到恢复后,该值变为垃圾。谁能帮助我?

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

推荐答案

范围是本地功能的getName(),您正在返回通过名称南地址指针

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 = malloc(sizeof(char)*10);

此外,可以bufferoverun不使用得到(),不喜欢:

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

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

您还没有需要使用名称一个额外的变量简单的回南还是不错的。

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天全站免登陆