谁能告诉我为什么这段代码崩溃了?这很简单,如果字符串的长度大于16,请再次询问字符串.如果我在if语句中写入control = 1,它会起作用,但如果没有它,它应该工作相同,因为那时控制的值是1,我是对的吗?泰恩斯(我正在学习)
#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 );
}
Run Code Online (Sandbox Code Playgroud)
小智 8
char word [16]为字符串分配16个字节的存储空间.
然后scanf()将字符串读入该存储区.
如果读入的内存超过分配的存储量,则存储在存储结束后会损坏.
这就是你崩溃的原因.
| 归档时间: |
|
| 查看次数: |
282 次 |
| 最近记录: |