strcpy函数使用方法以及底层实现

strcpy(s1, s2);   strcpy函数的意思是:把字符串s2中的内容copy到s1中。连字符串结束标志也一起copy.
这样s1在内存中的存放为:ch;

在cout<<s1<<endl时,结果为ch;其实,在内存里面是这种存储结构:chna

假设说s1的长度是6,那是错误的. 你没有弄清strlen与sizeof的意思。

strlen函数的意思是測试字符串的字符长度,不含字符串结束标志的。


sizeof是个运算符,它的结果是字符串在内存中的所占字节大小,它要把算进去的。

strcpy函数原型1:

char * strcpy(char *a,char *b)
{ while((*(a++)=*(b++))!=0);return a;}
strcpy函数原型2:

char *strcpy(char *strDest, const char *strSrc);//strDest为目标,strSrc为源
{
     assert((strDest!=NULL) && (strSrc !=NULL)); //假设两个为空则不用复制,直接中止
     char *address = strDest;       //用address指向strDest開始地址
     while( (*strDest++ = * strSrc++) != ‘’ ) //复制,直到源串结束;
        NULL ; //空操作
     return address ;    //返回strDest開始地址                       
}//就这个算法看来是多余.

#include <iostream>
#include <cstring>
using namespace std;

int main(int argc, char *argv[])
{
    char s1[6]="china" ,s2[3]="ch";
    cout << s1 << endl;                    //china
    cout << strlen(s1) << endl;         //5
    cout << sizeof(s1) << endl;         //6
    strcpy(s1, s2);
    cout << s1 << endl;                    //ch

    for(int i=0; i<5; i++)
    {
        cout << s1[i] << endl;  //c h   n a
    }
    cout << strlen(s1) << endl;         //2
    cout << sizeof(s1) << endl;         //6
    return 0;
}



原文地址:https://www.cnblogs.com/mthoutai/p/6919806.html