C Programming-Structures & Union
C Programming-Structures & Union
Introduction – need for structure data type – structure definition – Structure declaration –
Structure within a structure - Union - Programs using structures and Unions – Storage
classes, Pre-processor directives.
5.1 INTRODUCTION
DEFINING A STRUCTURE
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member. The format of the struct statement is as follows
The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of the
structure's definition, before the final semicolon, you can specify one or more structure
variables but it is optional. Here is the way you would declare the Book structure –
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name and the
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
structure member that we wish to access. You would use the keyword struct to define
variables of structure type. The following example shows how to use a structure in a program
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
return 0;
}
When the above code is compiled and executed, it produces the following result
Declaration of a Structure:
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
A "structure declaration" names a type and specifies a sequence of variable values (called
"members" or "fields" of the structure) that can have different types. An optional identifier,
called a "tag," gives the name of the structure type and can be used in subsequent references
to the structure type.
A structured data type is a compound data type which falls under user-defined
category and used for grouping simple data types or other compound data types.
This contains a sequence of member variable names along with their type/attributes
and they are enclosed within curl brackets.
Structure is a user-defined datatype in C language which allows us to combine data of
different types together.
Structure helps to construct a complex data type which is more meaningful.
It is similar to an Array, but an array holds data of similar type only.In structure, data
is stored in form of records.
A structure in C is a collection of items of different types. You can think of a structure
as a "record" is in Pascal or a class in Java without methods.
Structures, or structs, are very useful in creating data structures larger and more
complex than the ones we have discussed so far.
Object conepts was derived from Structure concept. You can achieve few object
oriented goals using C structure but it is very complex.
struct student {
char firstName[20];
char lastName[20];
char SSN[9];
float gpa;
};
A new datatype called student ,can use this datatype define variables of student type: struct
student student_a, student_b; or an array of students as struct student students[50];
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
#include <stdio.h>
struct student {
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
};
main()
{
struct student student_a;
strcpy(student_a.firstName, "Deo");
strcpy(student_a.lastName, "Dum");
strcpy(student_a.SSN, "2333234" );
student_a.gpa = 2009.20;
#include<stdio.h>
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
ADVANTAGES OF STRUCTURE:
A functional structure provides stability and efficiency, especially in large and
complex organizations, because everyone uses similar processes. This also allows
large businesses to take advantage of economies of scale.
DISADVANTAGE OF STRUCTURE:
o Since Goto statement is not used, the structure of the program needs to be
planned meticulously.
o Lack of Encapsulation.
o Same code repetition.
o Lack of information hiding.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
var n;
structure tagname_2
{
var_1;
var_2;
var_3;
.
.
.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
var_n;
}, mem1
} mem2;
mem2.mem1.var_1: This refers to the first member of the variable of the structure
tagname_1.
mem2.mem1.var_2: This refers to the second member of the variable of the structure
tagname_2.
We will take more examples to get clarity on how the syntax satisfies the working of the
nested structure.
Examples #1
struct employee
{
struct man
{
char name [20];
int age;
char dob[10];
} d;
int empid;
char desg[10];
} emp;
5.4 UNION:
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
A union is a special data type available in C that allows to store different data
types in the same memory location.
It can define a union with many members, but only one member can contain a
value at any given time.
Unions provide an efficient way of using the same memory location for
multiple-purpose.
DEFINING A UNION
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one member
for your program. The format of the union statement is as follows –
The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the union's
definition, before the final semicolon, you can specify one or more union variables but it is
optional. Here is the way you would define a union type named Data having three members i,
f, and str
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string
of characters. It means a single variable, i.e., same memory location, can be used to store
multiple types of data. You can use any built-in or user defined data types inside a union
based on your requirement.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
The memory occupied by a union will be large enough to hold the largest member of
the union. For example, in the above example, Data type will occupy 20 bytes of memory
space because this is the maximum space which can be occupied by a character string. The
following example displays the total memory size occupied by the above union −
Sample Program
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Sample Program
#include <stdio.h>
#include <string.h>
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Sample Program
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
char str[20];
};
int main( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
Now that struct Student is a declared type, additional variables of the same type can also be
created:
struct Student mike, carla;
It is also possible to create struct variables without creating a named struct type in the
process, however in this case it is not possible to create additional variables of the same type,
nor can they be passed to functions, etc. Even if other struct variables are created with the
same data types and field names in the same order, they are not considered the same type:
struct {
int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} alice, bill; // alice and bill are of the same type, but not the same as struct Student
struct {
int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} charlie, daniel; // charlie and daniel are the same type as each other, but not
anyone else.
Use of typedef with structs
typedef is a powerful tool that allows programmers to define and then use their own
data types. For example:
typedef int Integer;
Integer nStudents, nCourses, studentID;
Note that in the typedef statement, the newly defined type name goes in the place
where a variable name would normally go.
There are a few benefits of using typedef with simple types such as the example
above:
For readability, "Integer" may be easier to understand than "int".
The typedef can be easily changed later, ( say to "typedef long int Integer;" ), which
would then affect all variables of the defined type.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
The scope of struct type definitions ( with or without the use of typedef ) follows the
same rules as variable declarations.
Obviously this means that the struct definition must be within scope before variables
of that type can be declared.
If only one function needs to know about a particular struct definition, then it should
be defined inside that function, but if more than one function needs to know the
definition, then it should be defined globally. ( Even though the variables should still
normally be declared locally. )
Now that struct Student has been typedefed to the name "Student", additional
variables of the same type can also be created:
Student phil, georgina;
In this particular example the tag name and the newly defined type name are the same. This is
allowed, but not required. In fact it is not even necessary to have the tag name, so the
following would do the same thing:
typedef struct {
int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} Student;
Initializing variables of type struct
NESTED STRUCTS
Structs can be nested, either with previously defined structs or with new internally
defined structs. In the latter case the struct names may not be necessary, but scoping rules still
apply. ( I.e. if a new struct type is created inside another struct, then the definition is only
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
known within that struct. ) For example, in the following code the Date struct is defined
independently to the Exam struct, but the score and time structs are defined internally to the
Exam struct::
struct Date {
int day, month, year; };
struct Exam {
int room, nStudents;
struct {
int hour, minute;
bool AM;
} time;
placed on a word boundary. These variables are more quickly accessed. The field name is
not required for zero length bit fields. Structure bit fields must be of an integral type. Most
implementations treat them as unsigned.
Example:
struct Packed_data {
unsigned int is_element:1; /* = 1 if element *
unsigned int atomic_number:8; /* Maximum 128 */
unsigned int is_reactant:1;
unsigned int is_product:1;
unsigned int is_catalyst:1;
unsigned int Stock_Index:16; /* Maximum 65,535 */
} chemical_inventory[ 10000 ];
Each data item in the above array takes up one 32-bit word ( with four bits wasted ),
for a total of 10,000 words of storage for the entire array, as opposed to 60,000 words of
storage if bitfields were not used.
UNIONS
Unions are declared, created, and used exactly the same as struts, EXCEPT for one key
difference:
Structs allocate enough space to store all of the fields in the struct. The first one is stored at
the beginning of the struct, the second is stored after that, and so on.
Unions only allocate enough space to store the largest field listed, and all fields are stored at
the same space - The beginning of the union.
This means that all fields in a union share the same space, which can be used for any listed
field but not more than one of them.
In order to know which union field is actually stored, unions are often nested inside of structs,
with an enumerated type indicating what is actually stored there. For example:
typedef struct Flight {
enum { PASSENGER, CARGO } type;
union {
int npassengers;
double tonnages; // Units are not necessarily tons.
} cargo;
} Flight;
union {
unsigned int n;
unsigned char c[ 4 ];
} data;
// ( Code to read in nRead, from the user or a file, has been omitted in this
example )
data.n = nRead;
for( int i = 0; i < 4; i++ )
printf( "Byte number %d of %ud is %ud\n", i, nRead, data.c[ i ] );
auto
register
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
static
extern
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be
used within functions, i.e., local variables.
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It
should also be noted that defining 'register' does not mean that the variable will be stored in a
register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that
member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
i is 6 and count is 4
i is 7 and count is 3
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
When you have multiple files and you define a global variable or function, which will also be
used in other files, then extern will be used in another file to provide the reference of defined
variable or function. Just for understanding, extern is used to declare a global variable or
function in another file.
The extern modifier is most commonly used when there are two or more files sharing the
same global variables or functions as explained below.
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
#include <stdio.h>
extern int count;
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in
the first file, main.c. Now, compile these two files as follows
Storage classes in C
Storage Storage Initial Value Scope Life
Specifier
Auto Stack Garbage Within block End of block
Extern Data segment Zero Global multiple Till end of
files program
Static Data segment Zero Within block Till end of the
program
Register CPU register Garbage Within block End of block
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it
instructs the compiler to do required pre-processing before the actual compilation. We'll
refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in the first
column. The following section lists down all the important preprocessor directives −
1 #define
Substitutes a preprocessor macro.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
2 #include
Inserts a particular header from another file.
3 #undef
Undefines a preprocessor macro.
4 #ifdef
Returns true if this macro is defined.
5 #ifndef
Returns true if this macro is not defined.
6 #if
Tests if a compile time condition is true.
7 #else
The alternative for #if.
8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.
10 #error
Prints error message on stderr.
11
#pragma
Issues special commands to the compiler, using a standardized method.
PREPROCESSORS EXAMPLES
#define MAX_ARRAY_LENGTH 20
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the
current source file. The next line tells CPP to get myheader.h from the local directory and
add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
#ifndef MESSAGE
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if
you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define
DEBUG, so you can turn debugging on and off on the fly during compilation.
PREDEFINED MACROS
ANSI C defines a number of macros. Although each one is available for use in
programming, the predefined macros should not be directly modified.
1 __DATE__
The current date as a character literal in "MMM DD YYYY" format.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
2 __TIME__
The current time as a character literal in "HH:MM:SS" format.
3 __FILE__
This contains the current filename as a string literal.
4 __LINE__
This contains the current line number as a decimal constant.
5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.
#include <stdio.h>
int main() {
When the above code in a file test.c is compiled and executed, it produces the following
result
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
ANSI :1
PREPROCESSOR OPERATORS
A macro is normally confined to a single line. The macro continuation operator (\) is
used to continue a macro that is too long for a single line. For example
#define message_for(a, b) \
The stringize or number-sign operator ( '#' ), when used within a macro definition,
converts a macro parameter into a string constant. This operator may be used only in a
macro having a specified argument or parameter list. For example −
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void) {
message_for(Carole, Debra);
return 0;
}
When the above code is compiled and executed, it produces the following result
The token-pasting operator (##) within a macro definition combines two arguments. It
permits two separate tokens in the macro definition to be joined into a single token. For
example
#include <stdio.h>
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
When the above code is compiled and executed, it produces the following result −
token34 = 40
It happened so because this example results in the following actual output from the
preprocessor
This example shows the concatenation of token##n into token34 and here we have used
both stringize and token-pasting.
#include <stdio.h>
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions
PARAMETERIZED MACROS
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square a number as
follows
int square(int x) {
return x * x;
Macros with arguments must be defined using the #define directive before they can be used.
The argument list is enclosed in parentheses and must immediately follow the macro name.
Spaces are not allowed between the macro name and open parenthesis. For example
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following result
REFERENCE BOOK
1. E. Balaguruswamy Programming in ANSI C 6th Edition. P.191-198
2. Ashok N. Kamthane Programming in C.P. P.436-13
3. C Tutorial Points Link : https://www.tutorialspoint.com/cprogramming/c_structures.htm
4. C Geeks of Geeks Link : https://www.geeksforgeeks.org/structures-c/
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.