strcpy的主场迎战的memcpy [英] strcpy vs. memcpy

查看:121
本文介绍了strcpy的主场迎战的memcpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么的memcpy()和strcpy()之间的区别?我试图用一个程序的帮助下找到它,但都被赋予相同的输出。

  INT的main()
{
    个char [5] = {'S','A','\\ 0','C','H'};
    炭P [5];
    烧焦T [5];
    的strcpy(P,S);
    的memcpy(T,S,5);
    的printf(萨钦p是[%S],t为[%S],P,T);
    返回0;
}

输出

 萨钦p为[SA],t为[SA]


解决方案

  

怎样做才能看到这种效果


编译并运行该code:

 无效dump5(字符*海峡);诠释的main()
{
    个char [5] = {'S','A','\\ 0','C','H'};    烧焦membuff [5];
    炭strbuff [5];
    memset的(membuff,0,5); //初始化两个缓冲区空
    memset的(strbuff,0,5);    的strcpy(strbuff,S);
    的memcpy(membuff,秒,5);    dump5(membuff); //显示发生了什么
    dump5(strbuff);    返回0;
}无效dump5(字符*海峡)
{
    的char * p = str中;
    为(中间体n = 0时; N小于5 ++ n)的
    {
        的printf(%2.2倍,* P);
        ++磷;
    }    的printf(\\ t的);    P =海峡;
    为(中间体n = 0时; N小于5 ++ n)的
    {
        的printf(%C,* P * P:'');
        ++磷;
    }    的printf(\\ n,STR);
}

这会产生这样的输出:

  73 61 00 63 68 SA CH
73 61 00 00 00山

您可以看到,CH是由复制的memcpy(),而不是的strcpy()

What is the difference between memcpy() and strcpy()? I tried to find it with the help of a program but both are giving the same output.

int main()
{
    char s[5]={'s','a','\0','c','h'};
    char p[5];
    char t[5];
    strcpy(p,s);
    memcpy(t,s,5);
    printf("sachin p is [%s], t is [%s]",p,t);
    return 0;
}

Output

sachin p is [sa], t is [sa]

解决方案

what could be done to see this effect

Compile and run this code:

void dump5(char *str);

int main()
{
    char s[5]={'s','a','\0','c','h'};

    char membuff[5]; 
    char strbuff[5];
    memset(membuff, 0, 5); // init both buffers to nulls
    memset(strbuff, 0, 5);

    strcpy(strbuff,s);
    memcpy(membuff,s,5);

    dump5(membuff); // show what happened
    dump5(strbuff);

    return 0;
}

void dump5(char *str)
{
    char *p = str;
    for (int n = 0; n < 5; ++n)
    {
        printf("%2.2x ", *p);
        ++p;
    }

    printf("\t");

    p = str;
    for (int n = 0; n < 5; ++n)
    {
        printf("%c", *p ? *p : ' ');
        ++p;
    }

    printf("\n", str);
}

It will produce this output:

73 61 00 63 68  sa ch
73 61 00 00 00  sa

You can see that the "ch" was copied by memcpy(), but not strcpy().

这篇关于strcpy的主场迎战的memcpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆