c strncpy null是否终止 [英] c strncpy null terminated or not

查看:115
本文介绍了c strncpy null是否终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这份文件,它说:

char *strncpy(char *destination, const char *source, size_t num);

从字符串中复制字符 将source的前num个字符复制到destination.如果在复制num字符之前找到source C字符串的末尾(由空字符表示),则将destination填充为零,直到总共写入了num个字符它.

Copy characters from string 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.

如果源长度大于num,则在目标末尾没有隐式附加空字符.因此,在这种情况下,destination不应被视为以null终止的C字符串(这样读取它会溢出).

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

destinationsource不得重叠(重叠时更安全的方法请参见memmove).

destination and source shall not overlap (see memmove for a safer alternative when overlapping).

但我对以下说法感到困惑:

But I am confused by this statement:

在这种情况下,目的地不应被视为以null终止的C字符串(这样读取它会溢出)

in this case, destination shall not be considered a null terminated C string (reading it as such would overflow)

由于如果num > strlen(source),它将在末尾用'\0'填充,'\0'实际上是字符串中的空(终止)字符,为什么不将其视为以空终止的C字符串?

Since if num > strlen(source), it will pad with '\0' at the end, '\0' is actually a null (terminating) character in a string, why it shall not be considered a null-terminated C string?

我编写了以下代码进行验证:

I have written below code to verify:

  char from[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
  char to[1024];
  for (int i = 0; i < 1024; i++) {
      to[i] = 'e';
  }
  strncpy(to, from, 1024);
  printf("from %s\n", from);

它在以下输出中正常工作:

It works fine with below output:

from hello
to hello

推荐答案

正在谈论strlen(source)> num的情况.它只会复制num个字符,都不是NUL,也不会添加NUL.

It's talking about the case when strlen(source) > num. It will only copy num chars, none of which is a NUL and it will not add a NUL.

这篇关于c strncpy null是否终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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