【问题标题】:Array issues: Stack around the variable 'arr' was corrupted数组问题:变量“arr”周围的堆栈已损坏
【发布时间】:2017-05-30 09:35:45
【问题描述】:

我正在编写一个请求数组的函数,如果它找到一个大写字母,它应该将整行交换为大写字母。否则,它只会打印函数。 将 main 函数运行到该函数正在检查大写字母的部分是可以的,我得到了标题中提到的错误。

主要功能:

#include <iostream>
#include "FuncA.h"
#include "printarr.h"
using namespace std;

void main()
{
    char choice;
    do
    {
        cout << "Welcome, choose a function to continue: " << endl << "\n A for Uppercasing arrays. \n B for Column sum. \n C for String copying. \n D for exit" << endl;
        cin >> choice;
        switch (choice)


            case 'A':
                    funca();

        } 
        while (choice != 'D');

    }

以及相关功能:

#include <iostream>
#include "FuncA.h"
#include "printarr.h"
using namespace std;

void funca()
{
    int  rows = 0, cols = 0; //init
    cout << "how many rows? ";
    cin >> rows;
    cout << "\n how many cols? ";
    cin >> cols;
    char arr[][COLS] = {0};


    for (int i = 0; i < cols; i++) // input
    {
        for (int j = 0; j < rows; j++)
        {
            cin >> arr[i][j];
        }
    }

    for (int i2 = 0; i2 < cols; i2++) // capcheck and printing if caps not detected
    {
        for (int j2 = 0; j2 < rows; j2++)
        {
            if (arr[i2][j2] >= 90 || arr[i2][j2] <= 65)
            {
                printarr(arr, rows, cols);
            }
        }
    }



}

我该如何解决这个问题?我尝试更改 COLS 的大小(大小在 .h 文件中定义),但没有奏效。

【问题讨论】:

  • 欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.

标签: c++ multidimensional-array runtime-error


【解决方案1】:

您对arr 的声明等于char arr[1][COLS]。第一个“维度”的任何非零索引都将超出范围。

如果您想要一个在运行时设置大小的“数组”,请使用std::vector

std::vector<std::vector<char>> arr(cols, std::vector<char>(rows));

【讨论】:

  • 另外,根本没有检查cols 是否小于或等于COLS
猜你喜欢
  • 2019-08-17
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 2012-11-08
相关资源
最近更新 更多