gpt4 book ai didi

c - c中的简单if语句不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:58 25 4
gpt4 key购买 nike

谁能告诉我这段代码为什么会崩溃?很简单,如果字符串的长度大于16,就再求一个字符串。如果我在 if 语句中写 control = 1 它会起作用,但没有它它应该也能起作用,因为此时 control 的值为 1,对吗?thans(我正在学习)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(void)
{
int control = 1;
char word[16] ;
printf("Enter a word: ");

while(control == 1)
{
scanf("%s", word);

int len = strlen(word);
printf("Lenght is: %d\n", len);

if (len >= 16)
{
printf("Word lenght to long, enter a new one: ");
}

else
{
control = 0;
}

}
printf("This is the word: %s\n", word );

}

最佳答案

char word[16] 为字符串分配 16 个字节的存储空间。

然后 scanf() 将一个字符串读入该存储。

如果读入的数量超过分配的存储量,存储结束后内存就会损坏。

这就是你崩溃的原因。

关于c - c中的简单if语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11820733/

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