Structures and Unions in C
Structures and Unions in C
Structures in C
• The structure is a user-defined data type in C, which is used to store a collection of
different kinds of data.
• The structure is something similar to an array; the only difference is array is used to
store the same data types.
//Initialization
strcpy( C.WebSite, “abc.in");
strcpy( C.Subject, "The C Programming Language");
C.Price = 100;
//Print
Output:
printf( "WebSite : %s\n", C.WebSite); WebSite : abc.in
printf( "Book Author : %s\n", C.Subject); Book Author: The C Programming Language
printf( "Book Price : %d\n", C.Price); Book Price : 100
}
Unions in C
• Unions are user-defined data type in C, which is used to store a collection of different
kinds of data, just like a structure.
• However, with unions, information can be stored in one field at any one time.
• Syntax:
– typedef <existing_names_of_datatype> <alias__userGiven_name>;
• Example
– typedef signed long slong;
• slong in the statement as mentioned above is used for a defining a
signed qualified long kind of data type. Now the thing is this 'slong',
which is an user-defined identifier can be implemented in your program
for defining any signed long variable type within your C program.
• This means:
slong g, d;
will allow creation of two variables name 'g' and 'd' which will be of type
signed long and this quality of signed long is getting detected from the
slong (typedef), which already defined the meaning of slong in your
program.
Use of typedef in Structures
• The concept of typedef can be implemented for defining a user-defined data type
with a specific name and type. This typedef can also be used with structures of C
language.
Example:
• Syntax:
#include<stdio.h>
typedef struct #include<string.h>
{ typedef struct professor
{
type first_member; char p_name[50];
type sec_member; int p_sal;
}
type thrid_member; prof;
}
nameOfType; void main(void)
{
prof pf;
• typedef can be used with pointers as well: printf("\n Enter Professor details: \n \n");
printf("\n Enter Professor name:\t");
• Syntax: scanf("% s", pf.p_name);
typedef int* pntr; printf("\n Enter professor salary: \t");
pntr g, h, i; scanf("% d", &pf.p_sal);
printf("\n Input done ! ");
}