COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
USER DEFINED DATATYPES
STRUCTURE
UNION
TYPEDEF
DIFFERENCE BETWEEN STRUCTURE AND UNION
ENUMERATION (ENUM)
QUIZ SET 4
5. Structure in C
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will be
allocated for each separately.
It is a best practice to initialize a structure to null while declaring, if we don’t assign any
values to structure members.
Defining a Structure:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
Example:
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
6. Declaring a Structure Variable
It is possible to declare variables of a structure, either along with structure definition or
after the structure is defined. Structure variable declaration is similar to the declaration
of any normal variable of any other datatype.
Structure variables can be declared in following two ways:
1) Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
7. 2) Declaring Structure variables with structure definition
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
8. Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at
compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
9. Structure members cannot be initialized with declaration. For
example the following C program fails in compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared,
no memory is allocated for it. Memory is allocated only when
variables are created.
Structure members can be initialized using curly braces ‘{}’.
10. What is designated Initialization?
Designated Initialization allows structure members to be initialized in any order. This feature
has been added in C99 standard.
#include<stdio.h>
struct Point
{
int x, y, z;
};
int main()
{
// Examples of initialization using designated initialization
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};
printf ("x = %d, y = %d, z = %dn", p1.x, p1.y, p1.z);
printf ("x = %d", p2.x);
return 0;
}
11. Accessing Members of Structure
There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)
Let's see the code to access the id member of p1 variable by.
(member) operator.
p1.id
12. Example
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
} record;
int main()
{
record.id=1;
strcpy(record.name, "Sahil");
record.percentage = 82.7;
printf(" Id is: %d n", record.id);
printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n", record.percentage);
return 0;
}
13. Structure to Function#include <stdio.h>
struct student
{
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main()
{
struct student s1;
printf("Enter name: ");
scanf("%[^n]%*c", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
}
void display(struct student s)
{
printf("nDisplaying informationn");
printf("Name: %s", s.name);
printf("nAge: %d", s.age);
}
14. Structure to Pointer
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:n");
printf("Age: %dn", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
15. Limitation of Structure
The C structure does not allow the struct data type to be treated
like built-in data types.
We cannot use operators like +,- etc. on Structure variables.
C Structures do not permit data hiding. Structure members can be
accessed by any function, anywhere in the scope of the Structure.
C structures do not permit functions inside Structure.
C Structures cannot have static members inside their body.
C Programming language do not support access modifiers. So
they cannot be used in C Structures.
16. Uses of Structure in C
1. C Structures can be used to store huge data. Structures act as a database.
2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer’s memory size etc.
17. Typedef in C
Typedef is a keyword that is used to give a new symbolic name for the existing
name in a C program. This is same like defining alias for the commands.
It behaves similarly as we define the alias for the commands.
Syntax:
typedef <existing_name> <alias_name>
OR
typedef struct structure_name
{
data-type member-1;
data-type member-2;
data-type member-3;
data-type member-4;
}type_name;
Now, while declaring variables of this structure type, we can write type_name in place of
struct structure_name in the whole program.
GO TO TOPICS
19. Union in C
A union is a special data type available in C that allows to store different data
types in the same memory location.
C Union is also like structure, i.e. collection of different data types which are
grouped together. Each element in a union is called member.
Union and structure in C are same in concepts, except allocating memory for
their members.
Structure allocates storage space for all its members separately. Whereas, Union
allocates one common storage space for all its members
We can access only one member of union at a time. We can’t access all
member values at the same time in union. But, structure can access all member
values at the same time.
This is because, Union allocates one common storage space for all its members.
Where as Structure allocates storage space for all its members separately.
Many union variables can be created in a program and memory will be
allocated for each union variable separately.
GO TO TOPICS
20. Using normal variable Using pointer variable
Syntax:
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Syntax:
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
union student
{
int mark;
char name[10];
float average;
};
Example:
union student
{
int mark;
char name[10];
float average;
};
Declaring union using normal
variable:
union student report;
Declaring union using
pointer variable:
union student *report, rep;
21. Continue…
Using normal variable Using pointer variable
Initializing union using normal variable:
union student report = {100, “Mani”, 99.5};
Initializing union using pointer variable:
union student rep = {100, “Mani”, 99.5};
report = &rep;
Accessing union members using normal
variable:
report.mark;
report.name;
report.average;
Accessing union members using pointer
variable:
report -> mark;
report -> name;
report -> average;
22. Example#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Abhi");
strcpy(record1.subject, "Science");
record1.percentage = 69.25;
printf("Record1 values using Unionn");
printf(" Name : %s n", record1.name);
printf(" Subject : %s n", record1.subject);
printf(" Percentage : %f nn", record1.percentage);
// assigning values to record2 union variable
printf("Record2 values using Unionn");
strcpy(record2.name, "Crista");
printf(" Name : %s n", record2.name);
strcpy(record2.subject, "Maths");
printf(" Subject : %s n", record2.subject);
record2.percentage = 87.64;
printf(" Percentage : %f n", record2.percentage);
return 0;
}
23. Application of union
Unions can be useful in many situations where we want to use the same memory for two or
more members. For example, suppose we want to implement a binary tree data structure
where each leaf node has a double data value, while each internal node has pointers to
two children, but no data. If we declare this as:
struct NODE {
struct NODE* left;
struct NODE* right;
double data;
};
then every node requires 16 bytes, with half the bytes wasted for each type of node.
24. Difference between Structure and Union in C
C Structure C Union
Structure allocates storage space for all its members
separately.
Union allocates one common storage space for all its
members.
Union finds that which of its member needs high storage
space over other members and allocates that much space
Structure occupies higher memory space. Union occupies lower memory space over structure.
We can access all members of structure at a time. We can access only one member of union at a time.
Structure example:
struct student
{
int mark;
char name[6];
double average;
};
Union example:
union student
{
int mark;
char name[6];
double average;
};
For above structure, memory allocation will be like below.
int mark – 2B
char name[6] – 6B
double average – 8B
Total memory allocation = 2+6+8 = 16 Bytes
For above union, only 8 bytes of memory will be allocated since double
data type will occupy maximum space of memory over other data
types.
Total memory allocation = 8 Bytes
GO TO TOPICS
25. Enumeration in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign
names to integral constants, the names make a program easy to read and maintain.
enum flag {const1, const2, ..., constN};
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum
elements during declaration (if necessary).
Defining an Enum
enum enum_name
{
element1,
element2,
element3,
element4,
};
GO TO TOPICS
26. Example
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
27. Why enums are used?
An enum variable can take only one value.
#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
int main()
{
card = spades;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
28. Facts About enum
1. Two enum names can have same value. For example, in the following C
program both ‘Failed’ and ‘Freezed’ have same value 0.
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
29. 2. If we do not explicitly assign values to enum names, the compiler by default
assigns values starting from 0.
For example, in the following C program, sunday gets value 0, monday gets 1,
and so on.
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
30. 3. We can assign values to some name in any order. All unassigned names get
value as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}
31. 4. The value assigned to enum names must be some integeral constant, i.e., the
value must be in range from minimum possible integer value to maximum possible
integer value.
5. All enum constants must be unique in their scope. For example, the following
program fails in compilation.
#include<stdio.h>
enum state {working, failed};
enum result {failed, passed};
int main()
{
return 0;
}
32. 2. What is the value stored in variable s?
A. Integer
B. Float
C. Fundamental
D. User defined
1. Which category of datatype enum belongs to?
A. 100
B. 400
C. 300
D. 200
#include <stdio.h>
enum State {
stopped = 100,
starting = 200,
running = 300,
sleeping = 400
};
int main()
{
enum State s=starting;
printf(" %d ", s);
return 0;
}
GO TO TOPICS
33. A. d.f
B. d.str
C. d.i
D. All of them
3. Which of the above information in the program will
be displayed correctly?
Explanation:
This is because
the union will
store the latest
data that is
stored in it and
that will be shown
correctly.
union Data{
int i;
float f;
char str[20];
};
int main()
{
union Data d;
strcpy(d.str,"Hi there");
data.i=30;
data.f=400.52;
printf("d.str=%sn",d.str);
printf("d.f=%fn",d.f);
printf("d.i= %dn",d.i);
return 0;
}
34. A. No, we should use one of the data member at a time
B. Yes
C. No, None of the data will be displayed properly
D. No, But not sure why
4. Will the program produce proper output? If not, why?
union Data{
int i;
float f;
char str[20];
};
int main()
{
union Data d;
strcpy(d.str,"Hi there");
data.i=30;
data.f=400.52;
printf("d.str=%sn",d.str);
printf("d.i= %dn",d.i);
printf("d.f=%fn",d.f);
return 0;
}
35. A. 4 bytes
B. 8 bytes
C. 30 bytes
D. 38 bytes
5. What will be the output of the program?
Explanation:
Union members share a common memory space and will take the size of largest member.
Thus, str[30] will take 30 bytes and being the largest member that defines the size of the
union also.
union Data{
int i;
float f;
char str[30];
};
int main()
{
union Data d;
printf("Memory occupied by d=%dn",sizeof(d));
return 0;
}
36. 6. Is the below program correct? If not what is the
error?
A. The program has errors, the variable for structure date is not declared.
B. The program is correct
C. The program has errors, the reference of variable was required not the data type
D. Both 1 and 3 are correct
struct Date{
int d;
int m;
int y;
};
int main()
{
Date.d=9;
Date.m=3;
Date.y=2020;
return 0;
}
37. 7. Is there anything wrong in the above program?
A. Nothing wrong
B. Yes, the reference of today not required
C. Yes, members should use “.” instead of “->”
D. Both 2 and 3 are correct.
struct Date{
int d;
int m;
int y;
};
int main()
{
struct Date today;
today->d=18;
today->m=3;
today->y=2020;
return 0;
}
38. 8. What is the size of the variable “today”?
Assume that 64 bit computer is used.
A. 4 bytes
B. 6 bytes
C. 8 bytes
D. 12 bytes
#include<stdio.h>
struct Date{
int d;
int m;
int y;
};
int main()
{
struct Date today;
printf("%d",sizeof(today));
return 0;
}