[英]''Stack around the variable was corrupted". How to determine size of the array?
I am supposed to write a simple program that will allow the user to input their last name into the program.我应该编写一个简单的程序,允许用户在程序中输入他们的姓氏。 The program will then output their last name onto the screen.
然后程序会将他们的姓氏输出到屏幕上。 However, when I run the program I see the error "Stack around the variable last was corrupted".
但是,当我运行程序时,我看到错误“上次变量周围的堆栈已损坏”。 Luckily this is a very short program, however, I am still confused what exactly is causing the issue to occur.
幸运的是,这是一个非常短的程序,但是,我仍然很困惑究竟是什么导致了问题的发生。
I have tried changing the size of the array from the number of elements in it to the number of bytes in it.我尝试将数组的大小从其中的元素数更改为其中的字节数。 I attempted this since the array is made up of characters and not integers.
我尝试了这个,因为数组是由字符而不是整数组成的。
The assignment states that the entered array may not be larger than 10 (composed of 9 characters).赋值说明输入的数组不能大于 10 个(由 9 个字符组成)。 This is why the global variable "MAX" is present.
这就是为什么存在全局变量“MAX”的原因。
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
const int MAX = 10;
int main()
{
char last[MAX];
int size = 0;
cout << "Enter you last name with no more than 9 characters: "
<< endl;
cin >> last[MAX];
size = sizeof(last);
cout << "This is your last name: " << endl;
cin >> last;
return 0;
}
char last[MAX];
cin >> last[MAX];
The array has MAX element, and the index starts at 0. Which means the last element is at index MAX-1;该数组有 MAX 个元素,索引从 0 开始。这意味着最后一个元素在索引 MAX-1 处;
Stack around the variable last was corrupted
最后一个变量周围的堆栈已损坏
This is because you are accessing last[MAX]
, which is past the allocated memory for the array.这是因为您正在访问
last[MAX]
,它超出了为数组分配的内存。
It should be它应该是
cin >> last;
cin >> last[MAX];
should be应该
cin >> last;
but even better use std::string
instead of char array.但更好的是使用
std::string
而不是 char 数组。
last[MAX]
does out of bound access, (and would only allow to retrieve one char) last[MAX]
进行越界访问,(并且只允许检索一个字符)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.