Solution for Exercise 16-8

ex1608

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct bot {
    int xpos;
    int ypos;
};

struct bot initialize(struct bot b);

int main()
{
    const int size = 5;
    struct bot robots[size];
    int x;

    srand((unsigned)time(NULL));

    for(x=0;x<size;x++)
    {
        robots[x] = initialize(robots[x]);
        printf("Robot %d: Coordinates: %d,%d\n",
               x+1,robots[x].xpos,robots[x].ypos);
    }
    return(0);
}

struct bot initialize(struct bot b)
{
    int x,y;

    x = rand();
    y = rand();
    x%=20;
    y%=20;
    b.xpos = x;
    b.ypos = y;
    return(b);
}

Output

Robot 1: Coordinates: 10,5
Robot 2: Coordinates: 8,11
Robot 3: Coordinates: 15,6
Robot 4: Coordinates: 9,2
Robot 5: Coordinates: 15,4

Notes

* See the typecast at Line 18?

* By creating the structure externally, you can code functions that are of that structure's type, such as the initialize() function at Line 29. In fact, this method is the only way you can code a function that returns a structure.

* For a function to return a structure, the function must be declared of that structure type, as is done in Line 29.

* Structures are one method by which a function can "return" multiple values.