gpt4 book ai didi

c - 我的解决方案是否因文件大小和存储值而导致打印错误?

转载 作者:行者123 更新时间:2023-11-30 15:48:11 26 4
gpt4 key购买 nike

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

第 2 部分:另一部分是我必须从输入文件中读取像素信息并将其存储到二维数组中。每个像素都有 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]);
}
}
}

最佳答案

第 1 部分

  1. 函数应采用空参数 - 这意味着没有参数。
  2. 你想要一个或。如果宽度或高度太大,则会出错。
  3. 次要的样式注意事项,您应该在此处使用#defines,并且它们应该全部大写。

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

第 2 部分

您可以像现在这样循环遍历数组,但实际上欺骗要好得多。C 数组的数组或直数组是相同的东西,只是语法糖略有不同。

  1. 将整个文件读入数组,请参阅 Reading the whole text file into a char array in C获取实现提示。
  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 变量感到抱歉,这是我无法(也不想)打破的习惯。

关于c - 我的解决方案是否因文件大小和存储值而导致打印错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16907927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com