c - 由 strncpy 修改的程序的行为

标签 c string strncpy

考虑一下,

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/

相关文章:

c - 需要用 "*"做一半圣诞树

python 字符串插值与另一种方法

c - strcpy() 创建错误

c - 如何转义字符串中的字符并显示转义的字符?

c++ - 单个文件非验证 xml 解析器/阅读器

string - Haskell 的 `++` 有多懒?

在C中复制字符串的结尾

使用分配的内存将整数复制到整数

c++ - 需要从文本文件读取操作并在程序中执行它

python - 一个线性函数,用于根据 python 中的不同条件按升序、降序对列表的字符串列表进行排序