代码功能
输入输出字符串。
代码块
#include <stdio.h>
#include <stdlib.h>
/* Implementation of library function gets() */
char *gets(char *dest)//定义指针函数gets
{
int c = getchar();
char *p = dest; //定义一个指针变量p,p的内容为dest地址。
while (c != EOF && c != '\n') {
*p++ = c;
c = getchar();
}
*p = '\0';
return dest;
}
/* Read input line and write it back */
void echo()
{
char buf[4]; //定义一个定长数组,数组长度为4
gets(buf);
puts(buf);//输出字符串,puts函数中使用了printf函数
}
void call_echo()
{
echo();
}
/*void smash()
{
printf("I've been smashed!\n");
exit(0);
}
*/
int main()
{
printf("Type a string:");
call_echo();
return 0;
}
测试结果
测试结果解释
当字符串的长度<4时,正常输出,超过数组长度时,puts函数中printf遇到‘\n’才结束,计算机不会检测数组长度,所以也可以输出。