您的位置:首页 > 其它

关于子函数返回字符串问题集锦

2015-04-06 20:24 239 查看
Case1:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* getMem(void)
{
      char  p[] = "hello world";//这样子定义可以输出,但输出乱码。
      p[5] = 0x0;
      return p;
}

int main()
{
    char *s="fzz";
    s=getMem();
    printf("%s\n",s);
    return 0;
}


至于程序运行结果已经注明在程序中。那么为什么会乱码呢?依我自己的理解是:
字符串数组p是个局部变量,存在栈内。当子函数返回时,栈空间也会被销毁。那么返回的字符串首地址p对应的内存保存的已经不是hello world了。而是未知的。因此输出乱码。

Case 2:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* getMem(void)
{
      static char  p[] = "hello world";//可以输出,输出为hello;
      p[5] = 0x0;
      return p;
}

int main()
{
    char *s="fzz";
    s=getMem();
    printf("%s\n",s);
    return 0;
}
此处我们把字符串数组p定义为静态变量,存储在静态存储区。不随着子函数的返回而销毁。因此可以正常运行。

Case 3:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* getMem(void)
{
      char  *p = "hello world";//程序运行时出错 不能输出
      p[5] = 0x0;
      return p;
}

int main()
{
    char *s="fzz";
    s=getMem();
    printf("%s\n",s);
    return 0;
}


这里不能输出和case1有点相像,但又并不完全一样。因为字符数组中各元素的值是可以改变的(可以对他们再赋值),但字符指针变量指向的字符串常量中的内容是不可以被改变的。这是因为在C语言中只有字符变量和字符串常量,没有字符串变量,而常量是不可以改变的。因此p[5]=0x0本身就是错误的。尽管编译通过了,但运行还是会出错。此处与存储无关。因此加不加static结果都是一样的。

如:

char a[]="hello";

char *b="hello";

a[2]='r';//允许对字符变量赋值

b[2]='d';//错误,字符串常量不可改变。

Case 4:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* getMem(void)
{
      char  *p = "hello world";//程序可以运行 输出为"hello world"
      return p;
}

int main()
{
    char *s="fzz";
    s=getMem();
    printf("%s\n",s);
    return 0;
}


这是因为如果定义一个字符数组,它只是一个字符数组变量,随着函数的调用结束,该变量所占有的内存也随之释放,因此返回的值是任意的;但是,如果用指针,它始终指向分配的内存,直到释放掉,因此返回值为"hello
world"。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: