0

考虑,

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”)。

谁能解释这种行为?

-新手

4

2 回答 2

2

您的程序会导致未定义的行为。 s未初始化,并且strncpy(s,"hello",5);没有复制足够的字符来包含空终止符。

于 2014-03-31T15:22:25.120 回答
2

第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 部分

下面的代码是正确的。请注意, 的参数strncpy6

char s[10];
strncpy(s,"hello",6);
printf("Hello!! %s %d\n",s,strlen(s));
于 2014-03-31T15:27:47.337 回答