【发布时间】:2016-04-03 20:11:57
【问题描述】:
我只是运行这段代码,我得到的 n=1 不是我期望得到的。你能解释一下为什么会这样吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXRIGA 11
int main()
{
char s[MAXRIGA+2];
char a[MAXRIGA]="pippo";
strncpy(s, a, 1); // n=1
printf("%s", s);
return 0;
}
返回
pF
如果 n=2 或更多,我会得到我想要的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXRIGA 11
int main()
{
char s[MAXRIGA+2];
char a[MAXRIGA]="pippo";
strncpy(s, a, 2); // n=2
printf("%s", s);
return 0;
}
返回
pi
【问题讨论】:
-
试试
char s[MAXRIGA+2] = {0};。 -
请勿使用
strncpy,它不会像您认为的那样做。如果您认为自己知道,请再想一想并阅读 C 文档进行验证。 -
我对@987654328@函数的咆哮:the-flat-trantor-society.blogspot.com/2012/03/…
-
阅读 Keith 的专栏,内容丰富。请注意,
strncat也不是strcat的更安全版本,它只是限制附加到目标缓冲区的字符数的变体,但使用它来避免缓冲区溢出很麻烦。