char p[] = "hello world" 与 char *p = "Hello world" 的区别
2014-03-23 17:30
351 查看
请看两个程序: (1) char *GetString(void) { char p[] = "Hello world"; return p; } void main() { char *str = NULL; str = GetString(); cout << str << endl; } (2) char *GetString(void) { char *p = "Hello world"; return p; } void main() { char *str = NULL; str = GetString(); cout << str << endl; } 为什么(1)输出的是乱码,(2)能够输出 hello world 我觉得可能是指针字符串和数组字符串分配空间时的区别,有谁知道具体的吗?谢谢!
【答案】
"Hello world"作为静态字符串实际上存储在数据区,但写程序的人不知道这个地址,而程序本身知道。当某一函数以 { char p[] = "Hello world"; ...} 方式使用此静态字符串时,实际上相当于: char p[12]; strcpy(p, "Hello world"); .... p[12]是在栈里临时分配的。虽然p指向的内容是"Hello world", 但是这是复制品,不是原件。当函数结束,char p[]就被程序回收了,所以p[]的内容就不再是"Hello world"了。 但如果以char *p="Hello world"的方式使用,p指向的是静态字符串存储的位置,也就是说指向"Hello world"的原件,当然没有问题了。 如果想坚持用char p[]而不使用char *p, 有效方法必须是: { static char p[]="Hello world"; return p; } 原因我想很清楚了。static char []是静态的,存储在数据区。
相关文章推荐
- char str[] = "hello world";和char *str = "hello world";区别
- char str[] = "hello world";和char *str = "hello world";区别
- char p[] = "hello world" 与 char *p = "Hello world" 的差异
- char c[5]="hello"和char *p="hello"区别
- 关于笔试题 "在函数里char p[] = "hello world" 与 char *p = "Hello world""
- char *s1 = "hello"和char s2[]="world"的区别
- char *myString = "Hello-World!";和 char myString[] = "Hello-World!";
- 关于char * c="hello"与char c[]="hello"的区别
- 关于char * c="hello"与char c[]="hello"的区别
- 【转载】关于char * c="hello"与char c[]="hello"的区别
- “Hello, world" 粗略比较 C语言和Objective-C的区别
- 关于char * c="hello"与char c[]="hello"的区别(面试宝典)
- 关于 char p[]="hello world";与char *p="hello world";
- (void)printf("hello world"); int a=2; void(a);中的(void)有什么用?
- char *p="abc" 与 char p[]="abc" 的区别
- 17种"Hello World"!
- Linux Assembly "Hello World" Tutorial, CS 200
- 利用开发人员命令提示输出"Hello world"
- Java IDL: The "Hello World" Example Using the POA, a persistent server, and a persistent naming service
- [细节决定B度]之回首一瞥cout<<"Hello,world"<<endl;