[英]Run-Time Check Failure #2 - Stack around the variable 'input' was corrupted
I am trying to write a short simple C program where I am trying to store 5 numbers into an array and print them on screen. 我正在尝试编写一个简短的简单C程序,其中我试图将5个数字存储到数组中并将其打印在屏幕上。
Code is as following: 代码如下:
#define _CRT_SECURE_NO_WARNINGS
#define size 5
#include <stdio.h>
#include <stdlib.h>
int main (void){
int i,input[size];
printf("Please enter %d numbers",size);
for (i=0; i<=size-1;++i);{
scanf("%d",&input[i]);
printf ("Numbers you entered are: \n");
printf("%d",input[i]);}
return 0;
}
When I am inputting 1 2 3 4 5 as my 5 numbers to store them in array input[size]
, I am getting this following error : 当我输入1 2 3 4 5作为我的5个数字以将它们存储在数组
input[size]
,出现以下错误:
Run-Time Check Failure #2 - Stack around the variable 'input' was corrupted.
I know error is something to do with array input[size]
overflow. 我知道错误与数组
input[size]
溢出有关。 But I can't figure out how 1 2 3 4 5 are overflowing. 但是我不知道1 2 3 4 5是如何溢出的。
Thanks in advance. 提前致谢。
You have an incorrect semicolon here: 您的分号不正确:
for (i=0; i<=size-1;++i);{ // <---- Incorrect semicolon, braces
scanf("%d",&input[i]);
printf ("Numbers you entered are: \n");
printf("%d",input[i]);} // <---- ...closing brace here?
Your loop accomplishes nothing. 您的循环什么都不做。 After it completes,
i==5
, and the first value written by scanf
is at input[5]
(overrunning the buffer). 完成后,
i==5
, scanf
写入的第一个值在input[5]
(超出缓冲区)。
Additionally, your brackets make no sense and are not in the correct locations. 此外,您的括号没有意义,而且位置也不正确。 If you want to first read 5 numbers, then print your message, then print those 5 numbers, you need to iterate twice.
如果要先阅读5个数字,然后打印消息,然后再打印这5个数字,则需要重复两次。
So it is clear, here is your code, with standard indentation / bracket placement. 很明显,这是您的代码,带有标准的缩进/括号放置。 It should be clear that it doesn't make any sense:
应该清楚的是,这没有任何意义:
int main (void){
int i, input[size];
printf("Please enter %d numbers",size);
for (i=0; i<=size-1; ++i)
{
// Do nothing
}
// i=5 now
// Pointless block
{
scanf("%d",&input[i]); // i=5, overrunning buffer
printf ("Numbers you entered are: \n");
printf("%d",input[i]);
}
return 0;
}
Here's what your code should look like (with proper indentation and brackets): 这里是你的代码应该是什么样子(与适当的缩进和括号中):
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 5
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int i;
int input[SIZE];
printf("Please enter %d numbers:\n",SIZE);
for (i=0; i<=SIZE-1; ++i) {
scanf("%d", &input[i]);
}
printf("\nNumbers you entered are: \n");
for (i=0; i<=SIZE-1; ++i) {
printf("%d\n", input[i]);
}
return 0;
}
Input/Output: 输入输出:
Please enter 5 numbers:
6
5
4
3
2
Numbers you entered are:
6
5
4
3
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.