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;
}如:
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;
}
原文:http://blog.csdn.net/u010275850/article/details/44905339