我有视觉工作室错误调试断言失败

i have visual studio error debug assertion failed

本文关键字:调试 断言 失败 错误 工作室 视觉      更新时间:2023-10-16

在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;
}

您在此处删除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 的动态数组。

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