c++ - 尝试将文本文件加载到动态分配的二维数组中时出现“分段错误”错误
问题描述
我不确定究竟是什么导致了这个错误,因为代码工作了一段时间,但我一定是改变了一些东西,把它搞砸了,我再也无法让它再次工作了。
这是正在加载到二维数组中的文本文件中的数据:
10 8 0 255 255 255 0 0 255 255 255 0 255 0 255 255 0 0 255 255 0 255 255 255 0 255 255 255 255 0 255 255 255 255 255 0 255 255 0 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 0 255 255 0 255 255 255 0 0 0 255 255 255 255 0 0 0
10/8
是数组的长度/高度。imagecorrupted.txt
与上面相同,但它在数据中的某处有 a355
而不是 a 。255
这是我到目前为止提出的相关代码:
int** load(string imageFile, int &length, int &height) {
ifstream file(imageFile);
if(file.is_open()) {
file >> length; // Loads 10 into length
file >> height; // Loads 8 into height
int** array = new int*[height];
for(int i = 0; i < height; i++) {
array[i] = new int[length];
}
for(int i = 0; i < height; i++) {
for(int j = 0; j < length; j++) {
file >> array[i][j];
if(array[i][j] > 255 || array[i][j] < 0) {
cout << "Image is corrupted." << endl;
file.close();
return nullptr;
}
}
}
file.close();
return array;
}
else {
cout << "Unable to open file." << endl;
return nullptr;
}
}
void show(int **image, int length, int height) {
cout << "The height of the matrix is: " << height << endl;
cout << "The length of the matrix is: " << length << endl;
cout << "The matrix is: " << endl;
for(int i = 0; i < height; i++) {
for(int j = 0; j < length; j++) {
cout << " " << image[i][j];
}
cout << endl;
}
}
void invert(int **image, int length, int height) {
for(int i = 0; i < height; i++) {
for(int j = 0; j < length; j++) {
if(image[i][j] == 255) {
image[i][j] = 0;
}
else {
image[i][j] = 255;
}
}
cout << endl;
}
}
void free(int **image, int &length, int &height) {
if(image) {
for(int i = 0; i < height; i++) {
if(image[i]) {
delete[] image[i];
}
}
delete[] image;
}
}
int main() {
int height = 0;
int length = 0;
int** image = 0;
image = load("../resource/imagecorrupted.txt", length, height);
image = load("../resource/image.txt", length, height);
show(image, length, height);
invert(image, length, height);
show(image length, height);
free(image, length, height);
}
输出:
图像已损坏。 矩阵的高度为:8 矩阵的长度为:10 矩阵是: 0 255 255 255 0 0 255 255 255 0 255 0 255 255 0 0 255 255 0 255 255 255 0 255 255 255 255 0 255 255 255 255 255 0 255 255 0 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 0 255 255 0 255 255 255 0 0 0 255 255 255 255 0 0 0 // 一堆空格 -bash:第 x 行:xxxxx 分段错误
我应该补充一点,这是课堂上的一项作业,所以我在做某些事情时受到限制(例如,需要是二维数组而不是向量)。
解决方案
您已交换length
并height
in function show
。外循环应该是height
和内循环length
。
推荐阅读
- cpanel - 从不同的设备访问 Web 服务器 - ERR_CONNECTION_TIMED_OUT
- javascript - 将数组拆分为动态组
- c# - 如何聚合 IAsyncEnumerable 的结果
- php - Gmail API 限制
- java - 如何在 Java 中显示 \ 和 "?
- ios - 在 iOS 上使用广播扩展和 WebRTC 协议进行屏幕投射的内存限制问题
- c# - 如何使用 Firebase 管理 SDK 发送消息
- javascript - React JS 中的 Axios 发布请求
- android - 如何在 android 中通过键从 Firebase 实时数据库中删除值?
- html - div背景颜色不更新