gpt4 book ai didi

c - 为什么字符串终止不会发生在空字符处

转载 作者:行者123 更新时间:2023-12-01 15:05:56 25 4
gpt4 key购买 nike

为什么它在第二个字符串中打印空字符?

声明字符数组应该自动在末尾添加空字符。这取决于编译器吗?

#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;
}

输出1:

:7::4::11::11:一个:0

:0::1::2::-97::-97:b:0

最佳答案

你在这里比较指针,换句话说,如果 str 设置为 NULL:

while(str != NULL) /* str holds the address of a char */

您需要将字符与空终止符进行比较,换句话说,检查字符str 指向是否为空终止符终止符:

while(*str != '\0')

关于c - 为什么字符串终止不会发生在空字符处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26531383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com