| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 608 人关注过本帖
标题:拷贝字符串出现的问题
只看楼主 加入收藏
beardark
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2009-8-18
结帖率:0
收藏
已结贴  问题点数:20 回复次数:2 
拷贝字符串出现的问题
#include<stdio.h>
#include<string.h>
main()
{
    static char *s="Chinese";
    static char *t="American";
    printf("\n\ns=%s",s);
    printf("\nt=%s",t);
    strcpy(s,t);
         printf("Copy After:\n");
    printf("\ns=%s",s);
    printf("\nt=%t",t);
}
结果为:
s=Chinese
t=American
Copy After:
s=American
t=
为什么拷贝完字符串后t的值会丢失?如果不定义成常量,用scanf函数读入两个相同的字符串,再进行复制拷贝,就不会出现字符串丢失现象。什么地方出错了?请高手指教。

#include<stdio.h>
#include<string.h>
main()
{
    char *s,*t;
         scanf("%s%s",s,t);
    printf("\n\ns=%s",s);
    printf("\nt=%s",t);
    strcpy(s,t);
         printf("Copy After:\n");
    printf("\ns=%s",s);
    printf("\nt=%t",t);
}
结果为:
s=Chinese
t=American
Copy After:
s=American
t=American
搜索更多相关主题的帖子: 拷贝字符串出现的问题 
2009-08-18 15:20
soler
Rank: 9Rank: 9Rank: 9
等 级:蜘蛛侠
帖 子:181
专家分:1077
注 册:2005-7-16
收藏
得分:10 
C99标准   第130页  
   
  32   EXAMPLE   8   The   declaration  
  char   s[]   =   "abc",   t[3]   =   "abc";  
   
  defines   "plain"   char   array   objects   s   and   t   whose   elements   are   initialized   with   character   string   
  literals.  
   
  This   declaration   is   identical   to  
  char   s[]   =   {   'a',   'b',   'c',   '\0'   },  
  t[]   =   {   'a',   'b',   'c'   };  
  The   contents   of   the   arrays   are   modifiable.   
   
  On   the   other   hand,   the   declaration  
  char   *p   =   "abc";  
  defines   p   with   type   "pointer   to   char"   and   initializes   it   to   point   to   an   object   with   type   
  "array   of   char"   with   length   4   whose   elements   are   initialized   with   a   character   string   literal.   
  If   an   attempt   is   made   to   use   p   to   modify   the   contents   of   the   array,   the   behavior   is   undefined.   

这个要看编译器的,
一般情况下我是这么理解的,char   *p中p指向常量数据段,且p是可变的,它指向的内容的修改要看你的编译器是否支持了。char   p[]中p指向局部数据段

你第一个例子最好改成字符数组形式。
2009-08-18 16:02
angle0000
Rank: 2
等 级:论坛游民
帖 子:4
专家分:24
注 册:2009-8-8
收藏
得分:10 
这样看看就清楚了

main()
{
    static char s[]="Chinese";
    static char *t="American";
    char* p=t;
    printf("\ns=%s",s);
    printf("\nt address:%p t=%s",t,t);
    strcpy(s,t);
         printf("\nCopy After:\n");
    printf("\ns=%s",s);
    printf("\nt address:%p t=%s",t,t);
    printf("\np address:%p p=%s",p,p);
}
2009-08-19 19:11
快速回复:拷贝字符串出现的问题
数据加载中...
 
   



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

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