函数strncpy文档方面的疑问 [英] strncpy documentation question

查看:129
本文介绍了函数strncpy文档方面的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下关于函数strncpy http://www.cplusplus.com/reference/clibrary/cstring/strncpy/ ,它提到的以下内容:

At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:

没有空字符隐式添加到目的地的末尾,这样的目标只会空值终止,如果在源中的C字符串的长度小于NUM。

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

什么是这句话是什么意思?

What is meant by this sentence?

推荐答案

这意味着,例如,如果您的源字符串是20个字符加上空终止和你的函数strncpy 指定少于21个字符,目标字符串将不会有附加了空。

It means that, for example, if your source string is 20 characters plus a null terminator and your strncpy specifies less than 21 characters, the target string will not have a null appended to it.

这是因为它的工作方式:函数strncpy 保证它会写明N个字节,其中N是传入的长度值

It's because of the way it works: strncpy guarantees that it will write exactly N bytes where N is the length value passed in.

如果源字符串(没有空字节)的长度小于,则它会用空的目标区域。如果是相等或更大,你不会得到一个空添加到目标。

If the length of the source string (sans null byte) is less than that, it will pad the destination area with nulls. If it's equal or greater, you won't get a null added to the destination.

这意味着它可能不是在技术上是你得到一个C字符串。这可以用code等来解决:

That means it may not technically be a C string that you get. This can be solved with code like:

char d[11];          // Have enough room for string and null.
strncpy (d, s, 10);  // Copy up to 10 bytes of string, null the rest.
d[10] = '\0';        // Then append null manually in case s was too long.

您分配11个字节(数组索引0..10),拷贝多达10个(索引0..9),然后设置11日(指数10)为null。

You allocate 11 bytes (array indexes 0..10), copy up to 10 (indexes 0..9) then set the 11th (index 10) to null.

下面,显示的是写各种大小的字符串到10个字符的区域与函数strncpy(D,S,10),其中 重新presents空字节:

Here's a diagram showing the three possibilities for writing various-sized strings to a 10-character area with strncpy (d, s, 10) where . represents a null byte:

s              d
-------------  ----------
Hello.         Hello.....
Hello Fred.    Hello Fred
Hello George.  Hello Geor

请注意,在第二和第三的情况下,没有空字节是这么写的,如果你把 D 作为一个字符串,你很可能在结果要失望了

Note that in the second and third case, no null byte is written so, if you treat d as a string, you're likely to be disappointed in the outcome.

这篇关于函数strncpy文档方面的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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