为什么数组多个接收值比它宣布举行 [英] Why can an array receive values more than it is declared to hold

查看:110
本文介绍了为什么数组多个接收值比它宣布举行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(void)
{
    char name1[5];
    int count;
    printf("Please enter names\n");
    count = scanf("%s",name1);
    printf("You entered name1 %s\n",name1);
    return 0;
}

当我进入了超过5个字符,它打印的字符作为我进入,这是超过5个,但字符数组被声明为:

When I entered more than 5 characters, it printed the characters as I entered, it was more than 5, but the char array is declared as:

char name1[5];

为什么发生这种情况。

Why did this happened

推荐答案

由于该字符的存储空间之后存储的地址。这是非常危险的,可能导致死机。

Because the characters are stored on the addresses after the 'storage space'. This is very dangerous and can lead to crashes.

例如。假设您输入的名字:迈克尔和变量名1开始在位于0x1000

E.g. suppose you enter name: Michael and the name1 variable starts at 0x1000.

name1: M       i     c      h      a      e      l     \0
      0x1000 0x1001 0x1002 0x1003 0x1004 0x1005 0x1006 0x1007
      [................................]

分配的空间被示出具有[...]
这意味着从0x1005内存将被覆盖。

The allocated space is shown with [...] This means from 0x1005 memory is overwritten.

解决方案:

仅复制5个字符(包括\\ 0结尾),或检查输入的字符串的长度复制之前。

Copy only 5 characters (including the \0 at the end) or check the length of the entered string before you copy it.

这篇关于为什么数组多个接收值比它宣布举行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆