Simple structs in C

Elementary data structures in any language are only convenient if the complexity of the problem being solved is low. Once data begins to become more complex, larger frameworks for encapsulating it are needed. This makes it easier to transfer data between subroutines, and essentially binds similar pieces of data together. In C, one such structure is aptly called a struct.

You don’t need to know anything about object-oriented programming, move along,

C is not an object-oriented language, so structs have nothing to do with objects. A struct is a type used to represent a heterogeneous collection of data, essentially a data aggregate. It is a mechanism for treating a set of different types as a single, coherent unit. For example, say we wanted to create a struct to hold data from a photograph (grayscale, with values 0-255):

struct image {
    int nrows;
    int ncols;
    int pixel[500][500];
    char date[9];
    int aperture;
    int ISOspeed;
};

This struct, named image contains a lot of information about the photograph, all encapsulated into one nice package, the constituent items of which are called members. Okay, so the storage associated with pixel seems kinda of small, at ¼ megapixel – but if you go to 1000×1000, at 1 MP this will be too large to store in a stack (and will require a dynamic array using the heap). It is then possible to create a variable, photo,  from the struct:

struct image photo;

Assigning data to the individual members can be easily performed:

photo.nrows = 400;
photo.ncols = 400;
strcpy(photo.date,"06111963");

But take note of the following. A struct declared as:

struct image {
    ...
}

is not the same as:

struct {
    ...
} image;

The first creates a struct named image, which can then be used to declare struct variables. The second defines image as a variable with this struct definition, but the definition cannot be re-used. If we try to declare a variable photo from this:

image photo;

The compiler will likely return a warning followed by an error, along the lines of:

warning: statement with no effect
error: expected ‘;’ before ‘photo’

More on that in the next post on typedef.

 

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