我正试图编写一个程序,将文本文件读取到结构的2D数组中,但试图将结构放入该数组会导致程序崩溃。
这是程序
ppm.c
#include "ppm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
image parse_ascii_image(FILE *fp) {
char magic[3];
char comm[1024];
char size[10];
image img;
int height;
int width;
... // some code
pixel **pixelarr;
printf("Commencing internal malloc...n");
if (height <= 1024 && width <= 1024 && height > 0 && width > 0){
pixelarr = (pixel **) malloc(height * sizeof(pixel*));
}else{
fprintf(stderr, "Error: Invalid image size: %d * %d", width, height);
return img;
}
for (int i = 0; i < height; i++){
pixelarr[i] = malloc(width * sizeof(pixel));
}
int d = 0;
int e;
printf("Filling in array:n");
for (int row = 0; row < height; row++){
for (int col = 0; col < width; col++){
for (int i = 0; i < 3; i++){
while ((e = fgetc(fp)) != 'n'){
d = d * 10;
e = e - 60;
d += e;
}
if (i == 0){
pixelarr[row][col].red = d;
}
if (i == 1){
pixelarr[row][col].green = d;
}
if (i == 2){
pixelarr[row][col].blue = d;
}
d = 0;
}
}
}
printf("Finished! Copying pixels over: n");
for (int row = 0; row < height; row++){
for (int col = 0; col < width; col++){
img.pixels[row][col] = pixelarr[row][col];
// ^^^This is where the program crashes
}
}
printf("Finished! Freeing internal malloc:n");
... // some more code
}
ppm.h:的相关信息
#ifndef PPM_H
#define PPM_H 1
#include <stdio.h>
...
typedef struct pixel pixel;
struct pixel {
int red;
int green;
int blue;
};
typedef struct image image;
struct image {
enum ppm_magic magic; // PPM format
char comments[1024]; // All comments truncated to 1023 characters
int width; // image width
int height; // image height
int max_color; // maximum color value
pixel **pixels; // 2D array of pixel structs.
};
...
// Parses an ASCII PPM file.
image parse_ascii_image(FILE *fp);
...
#endif
如果有人能帮我弄清楚是什么原因导致我的程序在那里崩溃,我将不胜感激。非常感谢。
几个问题:
1:img.pixels从未初始化。任何时候创建指向某个对象的指针而不首先为其赋值时,都可以尝试将其设置为NULL,这样更容易调试。请注意,这不会解决问题。要解决此问题,只需使用结构实例初始化它们
2:您应该释放pixelarr
。大多数现代操作系统都这样做,但这仍然是非常好的做法
3:不使用嵌套循环而使用img.pixels = pixelarr
不是更容易吗?它实现了相同的效果(除非这是针对类的,并且这部分是必需的(。