strncpy不会切断其余部分 [英] strncpy does not cut off the rest of the line

查看:123
本文介绍了strncpy不会切断其余部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!

我有一个char缓冲区:

  char  a [] =   test_string; 



现在我需要将3个字符复制到相同的缓冲区:

 strncpy(a,a, 3  ); 



结果我得到:

test_string

但我需要得到这个:

tes

为什么strncpy()函数不会切断剩下的行?为什么我不能使用相同的源和目标缓冲区?

解决方案

使用 strncpy(),目的地和来源不得重叠。如果你需要复制重叠的字符串,请改用 memmove()



但在你的情况下,两个函数都将没有得到预期的结果,因为如果它被传递的长度覆盖,两个函数将只复制终止空字符。



要截断字符串,只需设置终止空字符:

 a [ 3 ] =  0  


Hello!
I have one char buffer:

char a[] = "test_string";


Now I need to copy 3 characters to te same buffer:

strncpy(a, a, 3);


As a result I get:
test_string
But I need to get this:
tes
Why strncpy() function does not cut off the rest of the line? And why I can't use the same source and destination buffer?

解决方案

With strncpy(), destination and source shall not overlap. If you need to copy overlapping strings, use memmove() instead.

But in your case both functions will not get the expected result because both functions will only copy the terminating null character if it is covered by the passed length.

To truncate a string just set the terminating null character:

a[3] = 0;


这篇关于strncpy不会切断其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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