How to store large images in C without pointers

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.

Trick #1

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[2000][2000];

This array has a size of 4 million bytes.

Trick #2

The second trick, is rather sly. Create the array using static. For example:

static int image[2000][2000];

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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s