structs can be thought of as a container for multiple variables.
Lets say you have to keep track of 10 different people. For each one
you need to know their name, age, sex, weight. This would be a ton of
variables to keep around. You would need 10 different variables for the
name, 10 different for ages, 10 different for sex, etc...
Instead you can declare a struct that holds these variables.
(also called member variables because they are members of the struct)
struct Person
{
char name[ 64 ];
int age;
char sex;
int weight;
};
Then, to use it, you make instances of the struct..
//customer1 is now an instance of the Person struct.
Person customer1;
//access the member variables of the struct with the period (dot)
customer1.age = 45;
customer1.sex = 'M';
customer1.weight = 315;
strcpy( customer1.name, "John" );
//neat huh? now to print them out you can do...
printf( "age: %d", customer1.age );
now lets say you want to use pointers...
Person *pCustomer = &customer1;
above, pCustomer now points to memory the address of (&) customer 1.
You can still access the member variables, but you have to use the -> arrow.
(minus sign and greater than sign)
printf( "Age : %d", pCustomer->age );
__________________________________________________________
//This program will allow the user to
//input up to 10 customers and then print them all out.
#define _CRT_SECURE_NO_DEPRECATE
#include <string.h>
#include <stdio.h>
#include <conio.h>
struct Person
{
char name[64];
int age;
char sex;
int weight;
};
void PrintCustomerStruct( Person *pCustomer, int count )
{
int i;
for ( i = 0; i < count; i++ )
{
printf( "\n Name : %s", pCustomer[ i ].name );
printf( "\n Age : %d", pCustomer[ i ].age );
printf( "\n Sex: %c", pCustomer[ i ].sex );
printf( "\n Weight : %d", pCustomer[ i ].weight );
}
}
void main( void )
{
int count = 0;
int stop;
Person customer[ 10 ];
do
{
Person *pCustomer = &customer[ count ];
printf( "\n Enter name :" );
scanf( "%s", &pCustomer->name );
fflush( stdin );
printf( "\n Enter age :" );
scanf( "%d", &pCustomer->age );
fflush( stdin );
printf( "\n Enter sex, M or F :" );
scanf( "%c", &pCustomer->sex );
fflush( stdin );
printf( "\n Enter weight :" );
scanf( "%d", &pCustomer->weight );
fflush( stdin );
count++;
if ( count < 10 )
{
printf( "\n Continue? 1=yes or 2=no :" );
scanf( "%d", &stop );
}
}
while ( stop == 1 && count < 10 );
PrintCustomerStruct( customer, count );
getch( );
}