下面这段:
int main(){
char s[]="hello world";
char *n;
n=&s[0];
int t=strlen(n);
printf("%d\n",t);
}
得到字符长度是11,但是如果把char s[]="hello world";改为char s[11]="hello world";
最后的值就会变成17,多出来的6是怎么回事
另外 如果重写strlen方法
size_t strlen(const char *s){
int n;
for(n=0;*s!='\0';s++)
n++;
return n;
}
for循环里的*s!='\0'改成EOF 最后的结果就会变成24
char s[]="hello world"是直接在最后赋值‘\0’;而改为char s[11]="hello world"则是用11个那么大的地方存放你的字符串,然而并没有结尾,所以后者你不一定一直是17,因为他的’\0‘不一定就在后第6个位置。
char s[11]="hello world",这个没有给结束符留位置,s[12],最后一位设为结束符,否则strlen不知道到什么地方结束,能得到17算你幸运,没准还崩溃了呢
最后的结论应该是随机数
因为你的字符串没有结束符