Monday, August 06, 2012

Coding Lessons: Structs (Lessons 18)

So we've dealt with Arrays and strings and passing arrays and fields to and from functions.

Now we're going to look at structured data.

Structured data is basically a list of fields, those fields can have any type, the total memory for that block is then the combined memory requirements of all the little bits of data inside that structured data block.

You can think of a struct like a row of a table.
Where we can give that table row or block of data a name.

It's probably best to write out some code and explain what's going on.

to start with structured data is created with the keyword struct.

struct product

Here we're going to create a structured data type called product, inside this data type will be a product name and a product price.
The data types that are contained in the struct declaration then follow inside curly brackets.

struct product {
float price;
int stocklevel;
};


So that's our definition of our structured data set-up.

we do this using the struct keyword again, then the name of the struct that we're referring to, (because we could define multiple struct types) then what we want to call it.

struct product apples;

now we want to poke some data into the struct, and read some data out of it:

apples.price = 0.49;
apples.stocklevel= 12;

printf("You have a stock of %d apple(s) costing $%.2f", apples.stocklevel, apples.price);



#include<stdio.h>

int main()
{
struct product { float price; int stocklevel; };
struct product apples;
apples.price = 0.49;
apples.stocklevel= 12;

printf("You have a stock of %d apple(s) costing $%.2f", apples.stocklevel, apples.price);

}

No comments: