char p[] = "hello world" 与 char *p = "Hello world"
来源:互联网 发布:生物试剂原材料数据库 编辑:程序博客网 时间:2024/06/06 01:31
百度知道上看到的一个问题,数组和指针之间的差别。记录如下:
【问题】
请看两个程序:(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 []是静态的,存储在数据区。
【测试】
#include "stdio.h"char *GetString1(void){char p[]="Hello,world";return p;}char *GetString2(void){char *p="Hello,world";return p;}int main(int argc, char const *argv[]){char *str1=NULL;char *str2=NULL;str1=GetString1();str2=GetString2();printf("str1=%s\nstr2=%s\n",str1,str2 );return 0;}【结果】
jietang@ubuntu:~/src/demo13$ cc -Wall 1.c -o 11.c: 在函数‘GetString1’中:1.c:5:2: 警告: 函数返回局部变量的地址 [默认启用]jietang@ubuntu:~/src/demo13$ ./1str1= :v�������О`����y��/v�ʄ��������%_�p�x�str2=Hello,world
0 0
- char p[] = "hello world" 与 char *p = "Hello world" 的差异
- 关于 char p[]="hello world";与char *p="hello world";
- char p[] = "hello world" 与 char *p = "Hello world"
- char p[] = "hello world" 与 char *p = "Hello world" 的区别
- 关于笔试题 "在函数里char p[] = "hello world" 与 char *p = "Hello world""
- char *p="hello world"有什么问题
- char *p = "world";
- char *ptr = hello world
- 关于char* arr="hello world"与char arr[]="hello world"
- char *p= "hello"和char p[] = "hello"的区别
- char str[] = "hello world";和char *str = "hello world";区别
- char str[] = "hello world";和char *str = "hello world";区别
- char *myString = "Hello-World!";和 char myString[] = "Hello-World!";
- char a[] = "hello world1"和char *p = "hello world2";的区别
- char c[5]="hello"和char *p="hello"区别
- char a[] = "hello world1"和char *p = "hello world2";的区别
- char a[] = "hello world1"和char *p = "hello world2";的区别
- char *p="world" 這個里面的world為什么不能改变呢
- asterisk1.8启动信息分析(未完)
- Luapower
- Android图像处理(2):怀旧效果
- 阿里旺旺出现create DOMDocument instance error
- AFNetworking 2.0 介绍
- char p[] = "hello world" 与 char *p = "Hello world"
- 自定义主键的生成策略
- iOS的Drawing
- Letter Combinations of a Phone Number
- loongson开发板内核配置问题
- Properties与HashTable----API分析
- 养老金并轨列入今年政府重点工作 已有7套方案
- 勇闯FreeBSD(五)
- 麻省理工女博士