| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 861 人关注过本帖
标题:再谈字符串的定义,你有没有这样试过?
取消只看楼主 加入收藏
herotobe
Rank: 1
等 级:新手上路
威 望:1
帖 子:48
专家分:0
注 册:2006-5-3
收藏
 问题点数:0 回复次数:2 
再谈字符串的定义,你有没有这样试过?

对于用 char *p="China" 这样定义的字符串。教材中说,把字符串常量的首地址赋给p(教材中使用的编译器为Turbo C 2.0).而且我们大多数人认为这样定义后,字符串常量“China"的什不能修改。
那么请大家看下面的程序。

main()
{char *str;
str="thank you";
printf("the address of cosnt \"thank you \" is %p\n",str); /* 输出 字符串常量thank you的地址 */
printf("Enter your string:\n");
scanf("%s",str);
printf(" the address of const %s is %p",str,str);
getch();
}


程序运行结果为:the address of cosnt "thank you is 0840:0094
the address of cosnt " 输入的内容 " is 10840:0094
这不就是说明原来的字符常量thank you被输入的内容覆盖了吗?,因而实现的字符常量的修改。

如果要考察"thank you "是否还在内存中,可以在程序的开始用另一个指针变量p也指向"thank you",在程序的最后输出
p指向的内容,如果p指向的内容仍为"thank you "说明字符串常量"thank you "没有被修改;若p指向的内容为在程序运行时输入的内容说明字符常量"thank you "被修改

main()
{char *str,*p;
p= str="thank you";

printf("the address of cosnt \"thank you \" is %p\n\n\n\n",str); /* 输出 字符串常量thank you的地址 */
printf("Enter your string:\n");
scanf("%s",str);
printf("\n\n\nthe address of const %s is %p\n\n\n",str,str);
printf("*p=%s",p);
getch();
}


本人使用的编译器为MyTC v5.2

[此贴子已经被作者于2006-5-6 14:40:17编辑过]

搜索更多相关主题的帖子: 定义 字符 
2006-05-05 21:26
herotobe
Rank: 1
等 级:新手上路
威 望:1
帖 子:48
专家分:0
注 册:2006-5-3
收藏
得分:0 

不好意思,刚才程序上出了点问题


After all,tomorrow is another day!!!!
2006-05-05 22:21
herotobe
Rank: 1
等 级:新手上路
威 望:1
帖 子:48
专家分:0
注 册:2006-5-3
收藏
得分:0 
非常感谢大家提出宝贵的意见!!!!!!!!!!!!!

After all,tomorrow is another day!!!!
2006-05-05 22:22
快速回复:再谈字符串的定义,你有没有这样试过?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011223 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved