char c[]="hello"
是局部数据。
c[0] = ‘t‘; // ok
char * c = "hello"
全局数据,在静态存储区域。
*c = ‘t‘; // false
#include <stdio.h>
/* 例子一 */
const char * strA()
{
/* 正确 通过static开辟一段静态存储空间 */
static char str[] = "hello";
/* 错误 分配一个局部数据,函数结束内存的栈释放
返回后的结果是不确定的且不安全,随时都有被回收的可能*/
char str[] = "hello";
/* 正确 分配一个全局数组,内存的全局区域*/
char * str = "hello";
return str;
}
/* 例子二 */
int
main()
{
static char str1[] = "hello";
char str2[] = "hello";
char * str3 = "hello";
char * str4 = "hello";
printf("str1 = 0x%x\n", str1);
printf("str2 = 0x%x\n", str2);
printf("str3 = 0x%x\n", str3);
printf("str4 = 0x%x\n", str3);
/*
现象总结:
1、str1、str3、str4的地址始终不变。
2、str3、str4地址相同。
3、str2的地址在一直变量。
解释原因:
1、str1、str3、str4地址是在静态存储空间。
2、str3、str4在静态存储空间同字符串。
3、str2是在栈空间。
*/
}
/*
连续运行了5次
[root@localhost test_class]# ./a.out
str1 = 0x8049734
str2 = 0xbf921e42
str3 = 0x8048530
str4 = 0x8048530
[root@localhost test_class]# ./a.out
str1 = 0x8049734
str2 = 0xbfd174a2
str3 = 0x8048530
str4 = 0x8048530
[root@localhost test_class]# ./a.out
str1 = 0x8049734
str2 = 0xbfa84cd2
str3 = 0x8048530
str4 = 0x8048530
[root@localhost test_class]# ./a.out
str1 = 0x8049734
str2 = 0xbffd3472
str3 = 0x8048530
str4 = 0x8048530
[root@localhost test_class]# ./a.out
str1 = 0x8049734
str2 = 0xbf954982
str3 = 0x8048530
str4 = 0x8048530
*/
函数中char c[]="hello"与char * c = "hello"区别 -- C,布布扣,bubuko.com
函数中char c[]="hello"与char * c = "hello"区别 -- C
原文地址:http://blog.csdn.net/cy_cai/article/details/38267039