字符指针的迷惑
字符指针的疑惑
#include<stdio.h>
int main()
{
char a[10]="0123456789";
char *hello=a;
printf("the a is %s\n",a);
printf("the hello is %s\n",hello);
char b[10]={'0','1','2','3','4','5','6','7','8','9'};
char *test=b;
printf("the b is %s\n",test);
printf("the sizeof hello is %d\n",sizeof(hello));
printf("the sizeof a is %d\n",sizeof(a));
}
gcc 1_test.c
./a.out
the a is 0123456789
the hello is 0123456789
the b is 01234567890123456789 这一串是怎么多出来的?
------解决方案--------------------
字符串需要有结束符,这样改:
char b[11]={'0','1','2','3','4','5','6','7','8','9', '\0'};
------解决方案--------------------
C语言里字符串就是一串以('\0')结尾字符。只输出的话是不会报错的,它会一直输出直到遇到'\0'为止。你的输出只越界了几位说明刚好碰到了'\0'。
------解决方案--------------------
没有'\0'结束符提示的话,结果是不可欲知的!反正不会正确!
------解决方案--------------------
那么输出的结果取决于当时b后面何时出现0,0之前的都会输出,可以说是难料也可以说是随机,总之已经不在程序员的掌控之中。
#include<stdio.h>
int main()
{
char a[10]="0123456789";
char *hello=a;
printf("the a is %s\n",a);
printf("the hello is %s\n",hello);
char b[10]={'0','1','2','3','4','5','6','7','8','9'};
char *test=b;
printf("the b is %s\n",test);
printf("the sizeof hello is %d\n",sizeof(hello));
printf("the sizeof a is %d\n",sizeof(a));
}
gcc 1_test.c
./a.out
the a is 0123456789
the hello is 0123456789
the b is 01234567890123456789 这一串是怎么多出来的?
c
指针
------解决方案--------------------
字符串需要有结束符,这样改:
char b[11]={'0','1','2','3','4','5','6','7','8','9', '\0'};
------解决方案--------------------
C语言里字符串就是一串以('\0')结尾字符。只输出的话是不会报错的,它会一直输出直到遇到'\0'为止。你的输出只越界了几位说明刚好碰到了'\0'。
------解决方案--------------------
没有'\0'结束符提示的话,结果是不可欲知的!反正不会正确!
------解决方案--------------------
那么输出的结果取决于当时b后面何时出现0,0之前的都会输出,可以说是难料也可以说是随机,总之已经不在程序员的掌控之中。
那如果我刚才不加结束字符意味着什么呢?
字符串需要有结束符,这样改:
char b[11]={'0','1','2','3','4','5','6','7','8','9', '\0'};