#include <stdio.h> //for printf
#include <stdlib.h> //for rand, srand
#include <time.h> //to seed srand
//------------------------------------------
// STRUCTS #2: Cant have too much of a good thing
//------------------------------------------
//------------------------------------------
// Make sure you fully understand the first
// struct example before proceeding to this one.
//------------------------------------------
/*
This is the definition of our LOCATION struct again. Nothing different
from the first struct example.
*/
struct LOCATION
{
int x;
int y;
};
/*
Here we have a function that we'll be calling later which will take the
passed in variable of type LOCATION and randomly fill the x and y
members of it. Notice that we can accept the LOCATION struct as an
argument. Now that its been defined (above) its can be used just
like any other data type. Notice we can even have pointers of its type.
*/
void SetPlacement(LOCATION * ThisPerson)
{
/*
Heres the first unusal thing. Wheres the '.' operator we saw in the
first example? We cant use it here as 'ThisPerson' is a pointer. We
have to use the '->' operator to access the values pointed to by
ThisPerson. Remember, ThisPerson is just a pointer to the actual
variable, not the variable itself.
*/
ThisPerson->x = rand() % 40;
ThisPerson->y = rand() % 40;
}
//------------------------------------------
// MAIN
//------------------------------------------
int main(void)
{
int i; //used in for loops
/*
Here we are going to declare a single variable of type LOCATION. It
will be an array of type LOCATION. Notice anything unsual? Nope.
Didnt think so. Everything is working normally.
*/
LOCATION Us[5];
//Seed the random number generator
srand( (unsigned)time(NULL) );
//Now we randomly assign values to all the 'Us' variables. Notice
//that an array of a struct works just a normal array would.
for(i = 0; i < 5; i ++)
{
/*
Here we pass in the address of this element of the 'Us' array.
The SetPlacement function will randomly assign values to the
x and y members of it.
*/
SetPlacement( &Us[i] );
}
printf("Everyone is here!\n\n");
for(i = 0; i < 5; i ++)
{
//Now we display all the values of all the elements of 'Us'
printf("Person #%i is at %i X, and %i Y!\n", i, Us[i].x, Us[i].y);
}
return 0;
}