c - 关于 strcat()、strncpy()、strncat() 等字符串函数的问题?

标签 c string output strcat strncpy

代码1

int main()
{
    char str[]="abc";
    char str1[]="hello computer";
    strcat(str,str1);
    printf("the concatenated string is : %s\n",str);
    return 0;
}

输出- abchello computer

代码2

int main()
{
    char str[100];  //notice the change from code 1
    char str1[]="hello computer";
    strcat(str,str1);
    printf("the concatenated string is : %s\n",str);
    return 0;
}

输出- @#^hello computer

代码3

int main()
{
    char str[100];
    char str1[]="hello computer";
    strncpy(str,str1,5);
    str[5]='\0';   //external addition of NULL
    printf("the copied string is : %s\n",str);
    return 0;
}

输出- hello

代码4

int main()
{
    char str[100]="abc";
    char str1[]="hello computer";
    strncat(str,str1,5);
    printf("the concatenated string is : %s\n",str);
    return 0;
}

输出- abchello

问题

Q-1) 为什么 abchello computer显示在 code 1 中和 @#^hello computercode 2 ?垃圾来自哪里@#^来了吗?

Q-2) 为什么外部添加NULL '\0'strncpy() 中是必需的但不在strncat()如图code 3code 4分别?

注意- 如果在 code 4 中我做char str[100];然后@#^hello已显示,但字符串仍未添加 NULL 结束

最佳答案

代码1

char str[]="abc";
char str1[]="hello computer";
strcat(str,str1);

这会溢出 str。该行为是未定义的,可以假设任何输出(实际上,str1 可能正在被自身覆盖,这就是为什么您看到 abshel​​lo computer 作为输出)。

代码2

char str[100];  //notice the change from code 1
char str1[]="hello computer";
strcat(str,str1);

您在 hello computer 之前看到垃圾,因为 str 未初始化。碰巧它在第一个 NUL 之前的测试时包含 "@#^"

代码3

char str[100];
char str1[]="hello computer";
strncpy(str,str1,5);
str[5]='\0';   //external addition of NULL

这是正确的。 strncpy 复制 "hello computer" 的前五个字符并且不以 NUL 结尾。你应该自己做(就像你所做的那样)。如需进一步引用,请参阅 strcpy 的手册页:

The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

代码4

char str[100]="abc";
char str1[]="hello computer";
strncat(str,str1,5);

strncpystrncat 之间的一个区别是strncat NUL 终止结果字符串。来自 strncat 的手册页:

As with strcat(), the resulting string in dest is always null-terminated.

关于c - 关于 strcat()、strncpy()、strncat() 等字符串函数的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21290075/

相关文章:

c - #include <stdio.h> 和 printf() 有什么关系?

c - 制作共享对象错误时如何修复局部符号'不能使用?

C: 使用 pthreads 和程序不退出 for 循环

javascript - 如何使用 parseFloat 将字符串转换为数字?

javascript - 当我在字符串上使用 .split 和 .length 来查找某个字符在字符串中出现的次数时,为什么输出数字总是少一?

java - 字符串拆分和比较 - 最快的方法

python - Linux 输出重定向守护进程不工作

Python脚本需要将输出保存到文本文件

sas - 在 PROC FREQ 中抑制 "Frequency"文本

c - 当文件实际存在时 open() 文件不存在