有一段代码如下:
--------------------------------------------
void mystrcpy(char* s, char* t);main() {
    char* s2 = "this is a test.";
    char* s3 = "hello world.";    mystrcpy(s3, s2);
}void mystrcpy(char* s, char* t)
{
    while ( (*s++ = *t++) != '\0')
        ;
}
-------------------------------------Question:
s2 比 s3要长, 在copy过程中s3的存储空间
是如何分配的?

解决方案 »

  1.   

    main() {
        char* s2 = "this is a test.";
        char* s3 = (char *)malloc(sizeof(s2));    mystrcpy(s3, s2);
    }
      

  2.   

    修正一下:main() {
        char* s2 = "this is a test.";
        char* s3 = (char *)malloc(sizeof(s2));    mystrcpy(s3, s2);
        free(s3);
    }
      

  3.   

    用vc的话 不可以那样用strcpy的 因为你的程序中
    char* s2 = "this is a test.";
        char* s3 = "hello world.";会被认为是指向常量的指针
    而常量是不允许改变的
      

  4.   

    鄙人是在Unix环境。 不知道VC是怎么一回事情。上面的代码是从Ritchie的经典著作上抄的。
    我也认为有问题, 但不敢怀疑权威, 故问大家。
    看来鄙人太崇权威了。
      

  5.   

    原程序绝对是错误的,因为"string"为常字符串,是只读的。
    Ritchie恐怕是拿这个做反面教材吧.
      

  6.   

    关注,我对unix不熟但在windows编程环境下,上面代码应该是错误的。
    因为s3指向的常量字符串,不能对他进行写操作, 这里暂且不管s3所占的
    字节数比s2所占的要少!在vc中这样做吧:
    main() {
        char* s2 = "this is a test.";
        char* s3 = new char[strlen(s2)+1];    mystrcpy(s3, s2);
        delete []s3;
    }