Lecture Notes - Unit 5
Lecture Notes - Unit 5
Course Description:
This course is aimed at enabling the students to
Total 100%
Lecture Notes
UNIT V
Note
Elements in a structure can be of the same or different types. However, all elements in
the structure should be logically related.
C Variable, C Array and C Structure
A normal C variable can hold only one data of one data type
at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types
Data types can be int, char, float, double and long double
etc.
Figure 3 Example
Structure Declaration Format and Example
• SYNTAX
Structure Union
#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;}
Output: Memory size occupied by data : 20
By using normal variables and pointer variables
Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
int main()
{
union test p1;
p1.x = 65;
union test *p2 = &p1; // p2 is a pointer to union p1
printf("%d %c", p2->x, p2->y); // Accessing union members using pointer
return 0;
}
Output:
65 A
What is output of program ?
#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}
Output:20
What is output of program ?
#include <stdio.h>
union unionJob
{ char name[32];
float salary;
int workerNo;
} uJob;
struct structJob {
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{ printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
}
Assignment
• Introduction to typedef in C
• Example Program
• The typedef keyword allows the programmer to create a new data type
name for an existing data type.
SMALLINT i;
struct student
{
int mark [2];
char name [10];
float average;
}
Variable for the above structure can be declared in two ways.
typedef in struct
d1.f = 220.5;
printf( "d1.f : %f\n", d1.f);
return 0;
}
typedef in enum
– Convenience in naming