0

我正在尝试编写一个程序,将文本文件读入二维结构数组,但尝试将结构放入该数组会导致程序崩溃。

这是程序

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

如果有人可以帮助我找出导致我的程序在那里崩溃的原因,我将不胜感激。谢谢!

4

1 回答 1

1

几个问题:
1:img.pixels 从未初始化。每当您创建指向某事物的指针而不先为其分配值时,请尝试将其设置为 NULL 以便更容易调试。请注意,这不会解决问题。要修复它,只需使用结构实例初始化它们。
2:你应该自由pixelarr。大多数现代操作系统都会这样做,但这仍然是非常非常好的做法。
3:不使用嵌套循环会更容易img.pixels = pixelarr吗?它实现了相同的效果(除非这是针对一个类,并且这部分是必需的)。

于 2020-12-08T06:40:31.950 回答