我有 visual studio 错误调试断言失败
i have visual studio error debug assertion failed
在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
s 的动态数组。
但仍有改进的余地。例如 my_array()
构造函数在这里毫无意义,使用 []
运算符打印内容很奇怪, []
运算符中的文本 "Enter element ["
也有问题。
在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
s 的动态数组。
但仍有改进的余地。例如 my_array()
构造函数在这里毫无意义,使用 []
运算符打印内容很奇怪, []
运算符中的文本 "Enter element ["
也有问题。