我有visual studio错误调试断言失败

时间:2017-11-09 14:20:29

标签: c++ visual-studio dynamic-memory-allocation

在visual studio程序崩溃中:错误调试断言失败。我的代码有什么问题?没有语法错误。仅警告:删除数组表达式,转换为指针当我使用cmd标准编译器运行它时,它可以正常工作。

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;

#define max_size 100

class my_array{
    int* arr[max_size];
public:
    my_array() {}
    my_array(int size) {
        if (size <= 0 || size > max_size) {
            exit(1);
        }
        for (int i = 0; i < size; i++) {
            arr[i] = new int;
            cout << "Enter element [" << i + 1 << "] = ";
            cin >> *arr[i];
        }
    }
    ~my_array() {
        delete[] arr;
    }
    void operator[](int n) {
        cout << endl;
        for (int i = 0; i < n; i++) {
            cout << "Enter element [" << i << "] = " << *arr[i] << endl;
        }
    }
};

int main() {
    my_array array(6);
    array[5];

    return 0;
}

1 个答案:

答案 0 :(得分:2)

您正在此处删除arr

delete[] arr;

arr从未分配new。在原始程序中arr是指向int的固定大小的指针数组。

你可能想要这个:

class my_array {
  int *arr;
public:
  my_array() {}
  my_array(int size) {
    if (size <= 0 || size > max_size) {  // BTW this test isn't really necessary, as we
                                         // can allocate as much memory as available
                                         // anyway much more than just 100
      exit(1);
    }

    arr = new int[size];         // allocate array of size size
    for (int i = 0; i < size; i++) {
      cout << "Enter element [" << i + 1 << "] = ";
      cin >> arr[i];
    }
  }

  ~my_array() {
    delete[] arr;                // delete array allocated previously
  }

  void operator[](int n) {
    cout << endl;
    for (int i = 0; i < n; i++) {
      cout << "Enter element [" << i << "] = " << arr[i] << endl;
    }
  }
};

您没有固定大小的int指针数组,而是拥有int s的动态数组。

但仍有改进的余地。例如,my_array()构造函数在这里毫无意义,使用[]运算符打印内容以及"Enter element ["运算符中的文本[]很奇怪也值得怀疑。