won*_*and 2 c string null char
为什么它在第二个字符串中打印空字符?
声明字符数组应该在结尾处自动添加空字符.这取决于编译器吗?
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool ChckStrng(char *str);
void main()
{
char a[] = "hello";
char b[] = "abc";
printf("a:%d\n", ChckStrng(a));
printf("b:%d\n", ChckStrng(b));
}
bool ChckStrng(char *str)
{
int count[26];
while(str != NULL)
{
printf(":%d:\n", *str - 'a');
if(++count[*str - 'a'] > 1)
return false;
str = str + 1;
}
printf("end\n");
return true;
}
Run Code Online (Sandbox Code Playgroud)
输出1:
:7 :: 4 :: 11:11:a:0
:0 :: 1 :: 2:: - 97 :: -97:b:0
你在这里比较指针,换句话说,如果str设置为NULL:
while(str != NULL) /* str holds the address of a char */
Run Code Online (Sandbox Code Playgroud)
您需要将字符与null终止符进行比较,换句话说,检查字符是否str 指向 null终止符:
while(*str != '\0')
Run Code Online (Sandbox Code Playgroud)