字符串结尾

li4c 2014-11-15 03:23:10
c语言中,我们用数组来保存字符串,最后用'\0'来表示结尾。
那么下面这个例子,'\0'是哪里来的
#include<stdio.h>

int main() {
int i;
// your code goes here
char str[100];
scanf("%s",str);//并没有输入'\0'
printf("%s",str);
for(i = 0 ;i < 100;++i)
printf("str[%d] = %d\n",i,str[i]);
return 0;
}
/*
Input:
Hello


Output:
Hellostr[0] = 72
str[1] = 101
str[2] = 108
str[3] = 108
str[4] = 111
str[5] = 0 //结尾标志
str[6] = 4
str[7] = 8
str[8] = 0
str[9] = 0
str[10] = 0
str[11] = 0
str[12] = -1
.
.
.
*/

最后的疑问是:
我们在使用cin,scanf,gets,输入字符串的时候,'\0'哪里来的,我们并没有输入这个字符,难道是这些运算符和函数自己加的吗
...全文
327 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
fengswd 2014-11-17
  • 打赏
  • 举报
回复
\0就是0的转译字符,就是null的转译字符。要问null从哪来的?c库函数在运行开始前都要初始化buff的,用memset将buff清零。除去你填充的字符,剩下都是这东西了。
starytx 2014-11-17
  • 打赏
  • 举报
回复
编译器自带的结束符。
baiwei12 2014-11-17
  • 打赏
  • 举报
回复
、\0就是自带的啊。。。
mymtom 2014-11-17
  • 打赏
  • 举报
回复
scanf自己会加上结束符'\0' scanf s Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
mymtom 2014-11-17
  • 打赏
  • 举报
回复
scanf自己会加上结束符'\0' scanf s Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
luckylucky028 2014-11-17
  • 打赏
  • 举报
回复
#include<stdio.h> #include<string.h> int main() { int i; // your code goes here char str[100]={'h','e','l','l','\0','o'}; //scanf("%s",str); printf ("%u,%u\n",strlen(str),sizeof str); return 0; } 若是不想把'\0'打印出来就先计算长度,strlen函数可以计算字符串长度,不包括'\0'在内,如上的程序输出为 4,100
luckylucky028 2014-11-17
  • 打赏
  • 举报
回复
读入的是字符串,在数组中进行存储就是以‘\0’表示字符串结束,你可以试一个对对一个字符数组进行初使化,多加几个‘\0’,用字符串输出,程序是会输出第一个‘\0’之前的数据,因为已经表示字符串结束,如:#include <stdio.h> int main() { char a[10] = {'t','e','s','\0','t'}; printf("%s\n",a); return 0; } 只会输出tes
赵4老师 2014-11-17
  • 打赏
  • 举报
回复
http://www.microsoft.com/visualstudio/chs/downloads#d-2010-express 点开Visual C++ 2010 Express下面的语言选‘简体中文’,再点立即安装 scanf的源代码在C:\Program Files\Microsoft Visual Studio 10.0\VC\crt\src\input.c
baiwei12 2014-11-17
  • 打赏
  • 举报
回复
你逗把,,编译器自己就会加啊
正在无聊中 2014-11-15
  • 打赏
  • 举报
回复
当然是自己加的,而且是编译器干的,不是scanf等干的,比如这个被gcc编译后有一段: .LC0: db "%s\n", 0 (好像是则个样子吧……)
ryfdizuo 2014-11-15
  • 打赏
  • 举报
回复
看下scanf的汇编,
Sping 2014-11-15
  • 打赏
  • 举报
回复
scanf("%s",str); "%s"本身的意思就是表示读字符串,那字符串以什么结尾?'\0'!!!后面的倒是的确都是乱码值,因为是在函数内的内置类型。

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧