strncpy()是memcpy()的专业化吗? [英] Is strncpy() a specialization of memcpy()?

查看:57
本文介绍了strncpy()是memcpy()的专业化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是好奇(我们经常使用这些功能).我没有看到 strncpy() memcpy().值得一提吗?

Just curious to know (as we use these functions often). I don't see any practical difference between strncpy() and memcpy(). Isn't it worth to say that effectively,

char* strncpy (char *dst, const char *src, size_t size)
{
  return (char*)memcpy(dst, src, size);
}

还是我缺少任何副作用?有一个类似的早期问题,但找不到确切答案.

Or am I missing any side effect? There is one similar earlier question, but couldn't find an exact answer.

推荐答案

有区别,请参见链接到的 strncpy 页面的这一部分(强调我):

There is a difference, see this part of the strncpy page you linked to (emphasis mine):

将源的前num个字符复制到目标.如果在复制num个字符之前发现源C字符串的结尾(由空字符表示),则将目标填充为零,直到总数为已经写入了num个字符.

Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

因此,如果要复制的字符串短于限制,则 strncpy 填充零,而 memcpy 读取超出限制(可能调用未定义的行为).

So if the string to be copied is shorter than the limit, strncpy pads with zero while memcpy reads beyond the limit (possibly invoking undefined behaviour).

这篇关于strncpy()是memcpy()的专业化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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