指向类中多维数组的指针
pointers to multidimensional arrays in class
我试图编写一个程序,但在运行时出现分段错误(核心转储(。当我放置一个像 array_2d[10][1] 这样的定义数组时,问题解决了,但我需要为我的项目进行内存分配。这是我代码的简单版本:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
class Exam
{
private:
double** array_2d;
unsigned int num;
unsigned int num1;
public:
Exam();
void memoryallocation();
void show();
};
Exam::Exam()
{
num=10;
num1=1;
}
void Exam::memoryallocation ()
{
double** array_2d = new double*[num];
for (unsigned int i = 0; i < num ;i++)
{
array_2d[i] = new double[num1];
}
}
void Exam::show ()
{
ifstream file;
file.open("fish.txt");
for (unsigned int i = 0; i < num; i++)
{
for (unsigned int j = 0; j < num1; j++)
{
file >> array_2d[i][j];
cout<<array_2d[i][j]<<" ";
}
cout<<endl;
}
file.close();
}
int main()
{
Exam E;
E.memoryallocation();
E.show();
return 0;
}
在函数 Exam::memoryallocation ()
中,您再次声明array_2d。
void Exam::memoryallocation ()
{
array_2d = new double*[num]; //remove the redeclaration of array_2d
for (unsigned int i = 0; i < num ;i++)
{
array_2d[i] = new double[num1];
}
}
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”