The use of C gets and strcat

Examples are as follows:

#include<stdio.h>
#include<string.h> /*strcat头文件*/

int main()
{
	char s1[]="1,2,3,4,5",s2[]="qwer";
	gets(s1);
	puts("s1="); #会自动换行
	puts(s1);
	strcat(s1,s2);
	printf("s1的内存大小:%d\n",sizeof(s1));
	printf("%s\n",s1);
	return 0;
} 

Operation result: Enter ABC

ABC
s1=
ABC
s1的内存大小:10
ABCqwer

Gets will automatically convert the end sign and carriage return to \0, so the original string actually has the same memory size (check it with sizeof), but the next strcat connection starts with \0 in the first parameter string. of.

It can be seen that the memory size of s1 is 10 bytes, namely 1, 2, 3, 4, 5\0

After gets(s1) (assuming the input is ABC carriage return) s1 actually becomes ABC\03,4,5\0

When connecting, it starts from \0 after ABC, so it becomes ABCqwer

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/108901707