strcpy()无法正常工作

时间:2013-04-08 04:31:38

标签: c string strcpy

我目前正在编写一个程序,其中我遇到了strcpy()函数的另一种行为。这是它的简短演示...

我经历了以下问题:Strip first and last character from C string

//This program checks whether strcpy() is needed or not after doing the modification in the string 
#include <stdio.h>
#include <string.h>

int main()
{
        char mystr[] = "Nmy stringP";
        char *p = mystr ;
        p++;

        p[strlen(p)-1] = '\0';
        strcpy(mystr,p);
        printf("p : %s mystr: %s\n",p,mystr);

}

输出: -

p : y strnng mystr: my strnng

如果我不使用strcpy()函数,那么我得到

p : my string mystr : Nmy string 

为什么会这样?

2 个答案:

答案 0 :(得分:9)

标准说:

  

7.24.2.3

     

如果在重叠的对象之间进行复制,则行为是   未定义。

您可以使用memmove或其他方法。

答案 1 :(得分:1)

如果源和目标字符串重叠,则不能将strcpy用于重叠的内存位置。在这种情况下,行为未定义,如标准中所述。

但您可以使用temp内存位置进行交换,例如this

相关问题