C - Creating a global structure variable

Description

Creating a global structure variable

Demo

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

#define SIZE 5 //  w  ww.j  av  a 2s .  co  m

struct bot {
  int xpos;
  int ypos;
};

struct bot initialize(struct bot b);

int main()
{
  struct bot Spider[SIZE];
  int x;

  srand((unsigned)time(NULL));

  for (x = 0; x<SIZE; x++)
  {
    Spider[x] = initialize(Spider[x]);
    printf("Robot %d: Coordinates: %d,%d\n",
      x + 1, Spider[x].xpos, Spider[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);
}

Result

To pass a structure to a function, the structure must be declared globally.

The structure variable must be fully defined as the argument.

The return statement passes the structure back to the calling function.

Related Topic