0

I'm having trouble figuring out how to read in a ppm file into the standard input, storing the pixels in a 2- dimensional array of new_pix in C. I don't really know How to get it started. Thanks in advance!

1 Answer 1

1

I assume you can get the dimensions of the image from the file (call them W and H). If not, read about the format from wikipedia

Now, you need to allocate memory for the 2d-array you want to make. You will need a char **buf (assuming 8-bit grayscale. You can use long or long long for 32/64 bit images.

Next allocate the space for pointers where you will store the rows of the image.

buf=(char**)malloc(sizeof(char*)*H);

Next, you need to allocate space for each row and read it from stdin (you can use scanf in a loop).

for(int y=0;y<H;y++){
  buf[y]=(char*)malloc(sizeof(char)*W);
  for(int x=0;x<W;x++)
    scanf("%d",&buff[y][x]);
}

And you are done! Note that you will have to do checks on malloc return value and limit W and H to sane values if you plan to distribute the code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.