struct
struct
As we know that Array is collection of the elements of same type, but many time we have to
store the elements of the different data types. Suppose Student record is to be stored, then for
storing the record we have to group together all the information such as Roll, name, Percent
which may be of different data types. Ideally Structure is collection of different variables under
single name. Basically Structure is for storing the complicated data. A Structure is a
convenient way of grouping several pieces of related information together.
struct Tag {
Members
};
Where Tag is the name of the entire type of structure and Members are the variables within the
struct.
For example:
struct example {
int x;
};
struct example an_example; /* Treating it like a normal variable type
except with the addition of struct*/
an_example.x = 33; /*How to access its members */
struct database {
int id_number;
int age;
float salary;
};
int main()
{
struct database employee;
employee.age = 22;
employee.id_number = 1;
employee.salary = 12000.21;
}
The struct database declares that it has three variables in it, age, id_number, and salary. We can
use database like a variable type like int. We can create an employee with the database type as
we did above. Then, to modify it we call everything with the 'employee.' in front of it.
We can also return structures from functions by defining their return type as a structure type. For
instance:
employee.age = 50;
employee.id_number = 2;
employee.salary = 13000.21;
return employee;
}
As a final note, if we wish to have a pointer to a structure, to actually access the information
stored inside the structure that is pointed to, we use the -> operator in place of the dot (.)
operator. All points about pointers still apply.
An example:
#include <stdio.h>
struct xampl {
int x;
};
int main(void)
{
struct xampl structure;
struct xampl *ptr;
structure.x = 12;
ptr = &structure;
printf( "%d\n", ptr ->x );
return 0;
}
We need the & when dealing with structures and using pointers to them. The -> acts somewhat
like the * when does when it is used with pointers.
C – Structures:
• C arrays allow you to define type of variables that can hold several data items of the same
kind but structure is another user defined data type available in C programming, which
allows you to combine data items of different kinds.
• Structure is the collection of variables of different types under a single name for better
handling.
• Structures are used to represent a record, Suppose you want to keep track of your books
in a library. You might want to track the following attributes about each book:
• Title
• Author
• Subject
• Book ID
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 for your program.
With the declaration of the structure you have created a new type, called Books.
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
This program is used to store and access “id, name and percentage” for 3 students. Structure
array is used in this program to store and display records for many students. You can store “n”
number of students record by declaring structure variable as ‘struct student record[n]“, where n
can be 1000 or 5000 etc.
#include<stdio.h>
#include<stdlib.h>
struct student{
int id;
float marks;
char name[10];
};
void main()
{
struct student record[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter the student[%d] id:=",i);
scanf("%d",&record[i].id);
printf("Enter the student [%d] name:=",i);
scanf("%s",record[i].name);
printf("Enter the student[ %d] marks:=",i);
scanf("%f",&record[i].marks);
}
for(i=0;i<3;i++)
{
printf("Student[%d] id:= %d\n",i, record[i].id);
printf("Student[%d] name:= %s\n",i, record[i].name);
printf("Student[%d] marks:= %f\n\n",i, record[i].marks);
}
}
Write a C program to add two distances entered by user. Measurement of distance should be in
inch and feet.(Note: 12 inches = 1 foot)
#include<stdio.h>
#include<stdlib.h>
struct distance{
int feet;
float inch;
};
void main()
{
struct distance d1,d2,sum;
printf("Enter 1st distance:\n");
printf("Enter feet:=");
scanf("%d",&d1.feet);
printf("Enter inch:=");
scanf("%f",&d1.inch);
printf("Enter 2nd distance:\n");
printf("Enter feet:=");
scanf("%d",&d2.feet);
printf("Enter inch:=");
scanf("%f",&d2.inch);
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
while(sum.inch>12)
{
sum.feet= ++sum.feet;
sum.inch=sum.inch-12;
}
printf(" Feet := %d and Inch:= %f\n",sum.feet,sum.inch);
}
• A structure can be passed to any function from main function or from any sub function.
• Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.
• You would access structure variables in the similar way as you have accessed in the
above example:
Write a C program to create a structure student, containing name and roll. Ask user the name
and roll of a student in main function. Pass this structure to a function and display the
information in that function.
#include<stdio.h>
#include<stdlib.h>
struct student{
int roll;
char name[10];
};
void display(struct student stu);
void main()
{
struct student s1;
printf("Enter name of student:=");
scanf("%s",&s1.name);
printf("Enter roll of student:=");
scanf("%d",&s1.roll);
display(s1);
}
void display(struct student stu)
{
printf("Name of the student:=%s\n",stu.name);
printf("Roll of the student:=%d",stu.roll);
}
In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can
be accessed from called function. This concept is very useful while writing very big programs in
C.
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Passing structure to function by address/reference:
• The address location of structure variable is passed to function while passing it by
reference.
• If structure is passed by reference, change made in structure variable in function
definition reflects in original structure variable in the calling function.
• Exercise: Write a C program to add two distances(feet-inch system) entered by user. To
solve this program, make a structure. Pass two structure variable (containing distance in
feet and inch) to add function by reference and display the result in main function without
returning it.
•
Example–Passing structure to function by reference:
#include<stdio.h>
#include<stdlib.h>
struct distance{
int feet;
float inch;
};
void addition(struct distance d1,struct distance d2, struct distance *sum)
{
sum->feet=d1.feet+d2.feet;
sum->inch=d1.inch+d2.inch;
while(sum->inch>12)
{
sum->feet= ++sum->feet;
sum->inch=sum->inch-12;
}
}
void main()
{
struct distance dist1,dist2,dist3;
printf("Enter 1st distance:\n");
printf("Enter feet:=");
scanf("%d",&dist1.feet);
printf("Enter inch:=");
scanf("%f",&dist1.inch);
printf("Enter 2nd distance:\n");
printf("Enter feet:=");
scanf("%d",&dist2.feet);
printf("Enter inch:=");
scanf("%f",&dist2.inch);
addition(dist1,dist2,&dist3);
printf(" Feet := %d and Inch:= %f\n",dist3.feet,dist3.inch);
}
Here the structure is passed to another function by address. It means only the address of the
structure is passed to another function. The whole structure is not passed to another function with
all members and their values. So, this structure can be accessed from called function by its
address.
Example program to declare a structure variable as global:
Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a
program. In this scenario, we don’t need to pass the structure to any function separately.
Copy a structure:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student{
int id;
char name[10];
float marks;
};
void main()
{
struct student record1={ 1,"Tuhin",60.5};
struct student record2, *record3, *ptr, record4;
printf(" Record of Student1--record1 structure");
printf("\nID:=%d \nName:= %s\nMarks:=%f",record1.id,record1.name,record1.marks);
record2=record1;
printf("\nID:=%d \nName:= %s\nMarks:=%f",record2.id,record2.name,record2.marks);
ptr=&record1;
memcpy(ptr, &record1,sizeof(record1));
printf("\nID:=%d \nName:= %s \nMarks:=%f",ptr->id,ptr->name,ptr->marks);
record4.id=record2.id;
strcpy(record4.name,record1.name);
record4.marks=record2.marks;
printf("\nID:=%d \nName:= %s\nMarks:=%f",record4.id,record4.name,record4.marks);
}
Record of Student1--record1 structure
ID:=1
Name:= Tuhin
Marks:=60.500000
ID:=1
Name:= Tuhin
Marks:=60.500000
ID:=1
Name:= Tuhin
Marks:=60.500000
ID:=1
Name:= Tuhin
Marks:=60.500000
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student{
int id;
char name[10];
float marks;
};
typedef struct student comp;
void main()
{
comp record1={ 1,"Tuhin",60.5};
printf(" Record of Student1--record1 structure");
• There are 5 members declared for structure in above program. In 32 bit compiler,
• 4 bytes of memory is occupied by int datatype.
• 1 byte of memory is occupied by char datatype and
• 4 bytes of memory is occupied by float datatype.
• Please refer below table to know from where to where memory is allocated for each
datatype in contiguous (adjacent) location in memory.
• The pictorial representation of above structure memory allocation is given below.
• This diagram will help you to understand the memory allocation concept in C very easily.
Structure Padding:
• In order to align the data in memory, one or more empty bytes (addresses) are inserted
(or left empty) between memory addresses which are allocated for other structure
members while memory allocation. This concept is called structure padding.
• Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32
bit processor) from memory at a time.
• To make use of this advantage of processor, data are always aligned as 4 bytes package
which leads to insert empty addresses between other member’s address.
• Because of this structure padding concept in C, size of the structure is always not same as
what we think.
• For example, consider below structure that has 5 members.
• struct student {
int id1;
int id2;
char a;
char b;
float percentage;
};
As per C concepts, int and float datatypes occupy 4 bytes each and char datatype occupies 1 byte
for 32 bit processor. So, only 14 bytes (4+4+1+1+4) should be allocated for above structure.
• But, this is wrong. Do you know why?
• Architecture of a computer processor is such a way that it can read 1 word from
memory at a time.
• 1 word is equal to 4 bytes for 32 bit processor and 8 bytes for 64 bit processor.
• So, 32 bit processor always reads 4 bytes at a time and 64 bit processor always
reads 8 bytes at a time.
• This concept is very useful to increase the processor speed.
• To make use of this advantage, memory is arranged as a group of 4 bytes in 32 bit
processor and 8 bytes in 64 bit processor.
Example program for structure padding:
• This C program is compiled and executed in 32 bit compiler.
• Please check memory allocated for structure1 and structure2 of this program
Structure padding analysis for previous C program
• Whereas, memory for 5th member “percentage” is not allocated immediate next
to the end of member “c”
• There are only 2 bytes remaining in the package of 4 bytes after memory allocated
to member “c”.
• Addresses 1297339864 and 1297339865 are used for members “name and
c”. Addresses 1297339866 and 1297339867 only is available in this package.
• So, next 4 byte of memory package is chosen to store percentage data which is
from 1297339868 to 1297339871.
• Because of this, memory 1297339866 and 1297339867 are not used by the
program and those 2 bytes are left empty.
• So, size of structure1 is 16 bytes which is 2 bytes extra than what we think.
Because, 2 bytes are left empty.
Memory allocation for structure1
• Memory for structure2 is also allocated as same as above concept. Please note that
structure1 and structure2 are same. But, they differ only in the order of the
members declared inside the structure.
• 4 bytes of memory is allocated for 1st structure member “id1″ which occupies
whole 4 byte of memory package.
• Then, 2nd structure member “name” occupies only 1 byte of memory in next 4
byte package and remaining 3 bytes are left empty. Because,
3rd structure member “id2″ of data type integer requires whole 4 byte of memory
in the package. But, this is not possible as only 3 bytes available in the package.
• So, next whole 4 byte package is used for structure member “id2″.
• Again, 4th structure member “c” occupies only 1 byte of memory in next 4 byte
package and remaining 3 bytes are left empty.
• But, this is also not possible as only 3 bytes available in the package. So, next
whole 4 byte package is used for structure member “percentage”.
• So, size of structure2 is 20 bytes which is 6 bytes extra than what we think.
Because, 6 bytes are left empty.