Structures

Structures are a collection of variables related in nature (those variables can be different data types)

Question: How to create a structure?
Answer: Using "struct" keyword to build the structure definition (place it before and outside the main method; don't forget semicolon at the end)
Example:
struct record{
     char lastName[20];
     char firstName[20];
     int score;
};

record is now a structure tag which can be used to create instances of the structures

Simple program sample:

#include <stdio.h>
#include <string.h>

struct student{
char fName[10];
char lName[10];
int id;
float tuition;
};

int main(void){
/*CREATE INSTANCE OF STUDENT STRUCTURE*/
struct student s1;

/*ASSIGN VALUES TO MEMBERS*/
strcpy(s1.fName,"Thanh");
strcpy(s1.lName,"Lai");
s1.id = 789 ;
s1.tuition = 8801.50;

/*PRINT THE MEMBER CONTENTS*/
printf("\nFirst Name: %s", s1.fName);
printf("\nLast Name: %s", s1.lName);
printf("\nStudent ID: %d", s1.id);
printf("\nTuition: %f", s1.tuition);

return 0;
}


Output:

No Response to "Structures"

Post a Comment

 

Copyright © 2013-2014 Lai Duy Thanh All rights reserved.