Intro to structs

25 09 2011

Structs have been a part of the C programming language from nearly the beginning. They seem to be somewhat inspired by objects or, given C’s age, it could be the other way around. I am not really sure.

A struct is like an object, but simplified. A struct cannot have any methods. Without methods, you are left with a structured group of variables. When you create a C struct, you must first define a struct type. This is a lot like writing a class. You define how many variables the struct can hold and what their types are. Here is an example of a struct definition.

typedef struct {
int lengthInSeconds;
int yearRecorded;
} Song;

That was the struct definition. Now we can create several instances of that struct. You will need to create a new instance of the struct before using dot syntax to add values to the struct’s variables.

Song thisSong;

thisSong.lengthInSeconds = 145;
thisSong.yearRecorded = 1948;

Song theOtherSong;

theOtherSong.lengthInSeconds = 213;
theOtherSong.yearRecorded = 1994;

If you are a newcomer to C or a new programmer in particular, this may seem a bit strange. However, it can be very helpful to pass structured groups of variables around, especially if you are writing a C program that has to handle lots of data. For example, if you wanted to write a basic address book, you could use a “Person” struct to handle individual records, each with a name, address, phone number, et cetera. If you are looking to get into Mac or iOS programming, which use Objective-C you still might see C structs being used there, as well.

There is an excellent C tutorial over at Cocoa Dev Central. If you are new to C or just want to brush up, that one page should help a great deal. The example struct above came from that site.




Leave a Reply

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

You are commenting using your 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

%d bloggers like this: