strcpy,stpcpy函数

函数原型:extern char *strcpy(char *dest,char *src)

                     或者extern char *stpcpy(char *dest,char *src)

参数说明:dest为一个目的字符串的指针,src为一个源字符串的指针。
        
所在库名:#include <string.h>
  
函数功能:把src所指的以“/0”结束的字符串复制到dest所指的数组中。

返回说明:src和dest所指内存区域不可以重叠,而且要求dest必须有足够的空间来容纳src的字符串,返回指向dest结尾处“/0”的指针(可能返回的时NULL)。

其它说明:暂时无。

实例:

#include<string.h>
#include
<stdio.h>
int main()
{
    
char dest[100]="Hello,I am sky2098,I liking programing!";
    
char *src="gramk";
    
char *temp;

    temp
=strcpy(dest,src);
    
if(temp!=NULL)
    
{
        printf(
"%s ",temp);
    }

    
else
    
{
        printf(
"You cause an error! ");
    }

    
return 0;
}

在VC++ 6.0编译运行:

我们看下面一个出现内存异常实例:

#include<string.h>
#include
<stdio.h>
int main()
{
    
char *dest="Hello,I am sky2098,I liking programing!";
    
char *src="gramk gramk gramk gramk gramk gramk gramk gramk gramk gramk"//源串长度大于目的串
    printf(
"destlen:%d  srclen:%d",strlen(dest),strlen(src));  //打印出两个字符串的长度
    char *temp;

    temp
=strcpy(dest,src);
    
if(temp!=NULL)
    
{
        printf(
"%s ",temp);
    }

    
else
    
{
        printf(
"You cause an error! ");
    }

    
return 0;
}

在VC++ 6.0编译运行:

当然,也可以使用stpcpy来实现相同的拷贝字符串的功能。

目的串所分配的空间(39)不能容纳下源串(大小为59),所以出现内存异常。

原文地址:https://www.cnblogs.com/lgh1992314/p/5835376.html