Structures in C


General template for basic structure use

struct name_structure
{
  int field1;
  float field2;
  char field3[27];
};

void pass_whole_by_address(struct name_structure *);
void pass_whole_by_value(struct name_structure ); 


int main(void)
{
  struct name_structure  one, two, three = {1, 3.1453, "brenda"};


  one.field1 = 3;
  get_int(&two.field1);

  scanf("%f %s", &one.field2, one.field3);

  pass_whole_by_value(one);
  pass_whole_by_address(&one);

  return (0);
}


void pass_whole_by_value(struct name_structure one)
{
   printf("%d %f %s", one.field1, one.field2, one.field3);
}


void pass_whole_by_address(struct name_structure *one)
{
  printf("%d %f %s", (*one).field1, (*one).field2, (*one).field3);

  scanf("%d %s", &((*one).field1), (*one).field3);
}


General template using typedef - much easier to read


typedef struct name_structure
{
  int field1;
  float field2;
  char field3[27];
} MYNAME;

void pass_whole_by_address(MYNAME *);
void pass_whole_by_value(MYNAME ); 

void main(void)
{
  MYNAME one, two, three = {1, 3.1453, "brenda"};
  MYNAME many[3];

  one.field1 = 3;
  get_int(&two.field1);

  for (i = 0; i < 3; i++)
    scanf("%d %f %s", &many[i].field1, &many[i].field2, many[i].field3);
  
  pass_whole_by_value(many[1]);
  pass_whole_by_address(&many[2]);

}


void pass_whole_by_value(MYNAME one)
{
   printf("%d %f %s", one.field1, one.field2, one.field3);
}


void pass_whole_by_address(MYNAME *one)
{
  printf("%d %f %s", (*one).field1, (*one).field2, (*one).field3);

  scanf("%d %s", &(*one).field1, (*one).field3);
}


General template for structures that have a structure as a field


typedef struct new_one       
{
  int which, what;
} NEWONE;

typedef struct name_structure
{
  NEWONE wherefore;
  int field1;
  float field2;
  char field3[27];
} MYNAME;

void pass_whole_by_address(MYNAME *);
void pass_whole_by_value(MYNAME ); 

void main(void)
{
  MYNAME one, two, three = {1, 2, 3, 3.1453, "brenda"};
  MYNAME many[3];

  one.field1 = 3;
  get_int(&two.field1);
  get_int(&two.wherefore.which);

  for (i = 0; i < 3; i++)
    scanf("%d %f %s", &many[i].field1, &many[i].field2, many[i].field3);
  
  pass_whole_by_value(many[1]);
  pass_whole_by_address(&many[2]);

}


void pass_whole_by_value(MYNAME one)
{
   printf("%d %f %s", one.field1, one.field2, one.field3);
}

void pass_whole_by_address(MYNAME *one)
{
  printf("%d %f %s", (*one).field1, (*one).field2, (*one).field3);

  scanf("%d %s", &(*one).field1, (*one).field3);
}