79762568

Date: 2025-09-12 05:36:38
Score: 0.5
Natty:
Report link

Let me clarify a couple of things.

  1. There are no two-dimensional arrays in C (at least, not as they are in other languages). A char array[10][20] is just an array of arrays. That is, an array with 10 elements, where each element (ie. array[x]) is an array of chars (ie. a pointer to the first char in a continuous bunch of 20 chars). A char array[10*20] is a different thing: a single array of 10x20=200 elements where each element (ie. array[i]) is a char, and you can access any element using the formula array[y*iwid+x] (in your code, x is your column; y is your row) (assuming you store all columns of row 0, then all columns of row 1, etc).

  2. "If I pass the original array, image[iwid][ihei] the resulting saved image is garbled." That's because the function stbi_write_png() needs a one-dimensional array of chars, with one char per component (aka. channel) per pixel. Your "small images" code is just copying the array of arrays of pixels (image[iwid]Iihei]) into a one dimensional img[iwid*ihei*icha] array of chars (where each pixel is icha=4 chars wide, one char per RGBA component) (image[x][y].rgba[c] is copied into img[(y*iwid+x)*4+c]). You must do this.

  3. You didn't specified the "compile time error" you're getting for "big" arrays. But the problem may be related to allocating too much space into the stack (as local variables are allocated into the stack). You may need to allocate the array into the heap: unsigned char *img = malloc (iwid*ihei*icha). Don't forget to check for the return of malloc() and to free (img) when you're done. You may also use a vector (as @Pepijn said).

  4. "How does stbi know the end of a dynamically allocated array?". You just pass a pointer to the first element of the one-dimensional array (statically or dinammically allocated, it's the same). The pixels are arranged one by one, first all "columns" of the same row, then all "columns" of the second row, etc. Total number of pixels is iwid*ihei. Total number of bytes is iwid*ihei*icha (where icha is 4).

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @Pepijn
  • Low reputation (0.5):
Posted by: Diego Ferruchelli