考虑一下,
int main()
{
char s[10];
strncpy(s,"hello",5);
printf("Hello !!%s %d\n",s,strlen(s));
return 0;
}
当我运行这个程序时,没有打印任何东西。但是当我评论对 strncpy 的调用时,它会打印“Hello !! 0”。
用过ideone ("http://ideone.com/j1cdKp ")
当我使用 gcc 编译器 (Debian 7.4) 时,它给出了预期的输出(“Hello !!hello 6”)。
谁能解释这种行为?
-新手
最佳答案
第 1 部分
此代码会导致未定义的行为,因为您尝试打印未初始化的字符串 s
。
char s[10];
printf("Hello!! %s %d\n",s,strlen(s));
第 2 部分
此代码会导致未定义的行为,因为您尝试打印一个非空终止的字符串。带有给定参数的 strncpy
将复制“hello”,但不会复制尾随的空终止符。
char s[10];
strncpy(s,"hello",5);
printf("Hello!! %s %d\n",s,strlen(s));
第 3 部分
下面的代码是正确的。请注意,strncpy
的参数是 6
。
char s[10];
strncpy(s,"hello",6);
printf("Hello!! %s %d\n",s,strlen(s));
关于c - 由 strncpy 修改的程序的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22765547/