我试图在C中创建一个8x8棋盘格PGM

时间:2016-02-03 05:35:42

标签: c

您好我试图编写一个创建800x800像素PGM文件的C程序,然后用100x100像素交替的黑白方块填充文件。它编译得很好,在执行时冻结,结果PGM文件看起来只是一条很细的交替的黑白线。

kmain()

2 个答案:

答案 0 :(得分:6)

我看到的问题:

使用越界数组索引

for (row = 0;row <= iBoardSize; row++){
             ^^^^^^^^^^^^^^^^ Wrong. Should be row < iBoardSize
   for (col = 0;col <= iBoardSize; col++){
                ^^^^^^^^^^^^^^^^ Wrong. Should be col < iBoardSize
      if (col < iBoardSize)
         fprintf(image, "%d ", iPgmData[row][col]);
      else
         fprintf(image, "\n");
   }
}

该块可以简化为:

for (row = 0;row < iBoardSize; row++){
   for (col = 0;col < iBoardSize; col++){
      fprintf(image, "%d ", iPgmData[row][col]);
   }
   fprintf(image, "\n");
}

致电fwrite

fwrite(iPgmData, 1, iBoardSize*iBoardSize*sizeof(int *), image);

只有连续数据时才能使用fwrite。在你的情况下,你没有。我不清楚你希望通过这个电话完成什么。我删除了调用,输出文件是一个有效的PGM文件。

未正确free分配的内存

你有

free(iPgmData);

只释放为指针分配的内存。它没有释放指针所指向的内存。你需要使用:

for (i = 0; i < row;i++)
   free(iPgmData[i]);

free(iPgmData);

答案 1 :(得分:2)

发布的程序过于复杂,包含有关索引到数组以及如何将数据写入输出文件的几个问题。

以下代码包含注释,执行适当的错误检查并生成所需的图像文件。

#include <stdio.h>  // fopen(), fclose(), fprintf(), FILE
#include <stdlib.h>

#include <errno.h>  // errno
#include <string.h> // strerror()

#define MAX_ROWS    (800)
#define MAX_COLS    (800)
#define BOARD_SIZE  (800)
#define SQUARE_SIZE (100)

int main (int argc, char* argv[])
{
    int row; // image row index
    int col; // image column index


    if( 2 != argc )
    { // then required command line parameter missing
        fprintf( stderr, "USAGE: %s <PGM_filename>\n", argv[0]);
        exit( EXIT_FAILURE );
    }

    // implied else, correct number of command line parameters

    /* Open the PGM file */
    FILE* image = fopen(argv[1], "wb");
    if (!image)
    {
      fprintf(stderr, "Can't open output file %s for write, due to: %s\n", argv[1], strerror( errno ) );
      exit( EXIT_FAILURE);
    }

    /*Write the header*/
    fprintf(image, "P5\n%d %d\n255\n", BOARD_SIZE, BOARD_SIZE);

    /* write the gray scale image */
    for (row = 0;row < BOARD_SIZE; row++)
    {
        for (col = 0;col < BOARD_SIZE; col++)
        {

            if( (row/SQUARE_SIZE)%2 == 0 )
            {
                if( (col/SQUARE_SIZE)%2 == 0 )
                {
                    fprintf( image, "%c", 255 );
                }

                else
                {
                    fprintf( image, "%c", 0 );
                }
            }

            else
            {
                if( (col/SQUARE_SIZE)%2 == 0 )
                {
                    fprintf( image, "%c", 0 );
                }

                else
                {
                    fprintf( image, "%c", 255 );
                }
            }
        }
    }

    fclose(image);

    return 0;
} // end function: main