So in the last post we looked at how to store large arrays dynamically in C. Is there any way to avoid this? Well, there are a couple of tricks.
When dealing with grayscale images, who only have values from 0-255 – which is literally how MOST images are stored. Even colour images contain tuples of Red-Green-Blue values all within the range 0-255. One way of course is to use a short datatype, which is typically smaller than an int, and takes less storage: 2 bytes versus 4 on many systems. But this is system dependent, and still there are many values not needed, i.e. 256-32K. So a better bet? Try using an unsigned char. These datatypes typically use 1 byte of information, so ¼ the data of an int, and they fit exactly in the 0-255 space needed.
Here is an 2000×2000 array created in this manner:
unsigned char image;
This array has a size of 4 million bytes.
The second trick, is rather sly. Create the array using static. For example:
static int image;
This means when the program runs, it will use statically allocated memory instead of the automatically allocated memory (i.e. the stack).
This array has a size of 16 million bytes.