0

第 1 部分:如果文件大小超过 500 x 500 测量值(在顶部定义为 max_width 和 height),我需要做的是打印出错误。我

第 2 部分:另一部分是我必须从输入文件中读取像素信息并将其存储到 2d 数组中。每个像素都有红色、绿色和蓝色 3 个值,但我不确定这是否重要。

我对解决方案的尝试:

第1部分:

void check_file_size //I'm not sure what to put as arguments since width/height are global
{
   if (width > 500 && height > 500)
   {
      perror("Error: File size too big.\n");
   }
}

第2部分:

#define max_width 500
#define max_height 500
int width, height

void read_header(FILE *new)
{
   int max_color;
   char P[10];

   fgets(P, 10, new);
   fscanf(new, "%d %d", &width, &height);
   fscanf(new, "%d", &max_color);
}

void store_into_array(FILE *input)
{
   int array[max_width][max_height];

   for (x = 0; x < width; x++)
   {
      for (y = height; y >=0; y--)
      {
         fscanf(input, "%d", &array[x][y]);
      }
   }
}
4

1 回答 1

1

第1部分

  1. 函数应该采用 void 参数 - 这意味着没有。
  2. 你想要一个或。如果宽度或高度太大,则会出错。
  3. 次要样式说明,您应该在这里使用#defines,它们应该全部大写。

void check_file_size(void) {
    if (width > MAX_WIDTH || height > MAX_HEIGHT) {
        perror("Error: File size too big.\n");
    }
}

第2部分

您可以像现在一样在此处循环遍历数组,但实际上作弊要好得多。数组的 AC 数组或直数组是相同的东西,但语法糖略有不同。

  1. 将整个文件读入数组,有关实现提示,请参阅将整个文本文件读入 C 中的 char 数组。
  2. 将缓冲区转换为您想要的最终结构。

// Make struct rgb match your data, details not supplied in the question
struct rgb {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
}

// Get width & height info as before

uint32_t buffer_size;
void* buffer;
load_file('filename', buffer, &buffer_size);

// Should verify that buffer_size == width * height * 3

struct rgb (*image_data)[width] = (struct rgb(*)[width])buffer;
// Note the above variable length array is a C99 feature
// Pre-C99 the same trick is a touch more ick

// Data can now be accessed as image_data[x][y].red; etc.

对变量感到抱歉stdint.h,这是我不能(也不想)打破的习惯。

于 2013-06-04T10:42:58.557 回答