Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4242382
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-05-12 22:11:47

    在上篇中 数组字符串与指针字符串 (四)   中,我们知道,数组字符串  和 指针字符串  不同的存储方式

      指针字符串:是将  字符串的地址 存储在 寄存器中,
     数组字符串: 将    字符串的内存存储在 寄存器中,如果字符串过大,是存储在 内存中



     在下面的程序中,我们 可以比较错误。
     通过 字符串复制写时,如果复制到指针型字符串时,出错
                             复制到数组字符串时,没有出错。 

       这是和 程序数据在内存中 分段机制有关

  1. #include <stdio.h>

  2. void copy_string(char *from,char *to);

  3. void main()
  4. {
  5.     char *a="i am a teacher.";
  6. //    char *b="you are a student.";   //复制出错  
  7.         char b[]="you are a student.";  //复制真确
  8.     printf("string a =%s\n string b = %s\n",a,b);
  9.     printf("copy string a to string b :\n");

  10.     copy_string(a,b);
  11.     
  12.     printf("\nstring a = %s\nstring b =%s\n",a,b);
  13. }

  14. void copy_string(char *from,char *to)
  15. {
  16.     for(;*from !='\0';from++,to++)
  17.     {
  18.         *to=*from;
  19.     }
  20.     *to='\0';
  21. }

//    char *b="you are a student.";   //复制出错
  1. ywx@yuweixian:~/yu/data-struct/c$ ./main
  2. string a =i am a teacher.
  3.  string b = you are a student.
  4. copy string a to string b :
  5. 段错误


char b[]="you are a student.";  //复制真确
  1. ywx@yuweixian:~/yu/data-struct/c$ ./main
  2. string a =i am a teacher.
  3.  string b = you are a student.
  4. copy string a to string b :

  5. string a = i am a teacher.
  6. string b =i am a teacher.



阅读(703) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~