You are on page 1of 52

Structure in C

Structure
A structure is a collection of variables of
different data types under a single name.
 The variables are called members of the
structure.
 Thestructure is also called a user-defined
data type.
Defining a Structure
Syntax:

struct structure_name
{
data_type member1;
data_type member2;
………………………………;
data_type memberN;
};
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
Publisher
Book ID

Example
struct Books
{
char title[50];
char author[50];
char publisher[50];
int book_id;
};
Cont..
Multiple variables of struct student type can be declared as:
struct Books b1, b2, b3;
Each variable of structure has its own copy of member
variables.
The member variables are accessed using the dot (.)
operator or member operator.

For example:
b1.title is member variable name of b1 structure variable
while b3.book_id is member variable book_id of b3
structure variable.
 // assign value to name of p1
#include <stdio.h>
 strcpy(p1.name, "George Orwell");
#include <string.h>

 // assign values to other p1 variables


struct Person {
 p1.citNo = 1984;
char name[50];
 p1. salary = 2500;
int citNo;
float salary;
 // print struct variables
} person;
 printf("Name: %s\n", p1.name);
 printf("Citizenship No.: %d\n", p1.citNo);
int main() {
 printf("Salary: %.2f", p1.salary);

// create Person variable


 return 0;
person p1;
 }
 Example:
Output:
struct student
{ Name: Rajkumar
char name[20]; ID: 1577
int ID; CSE Marks: 17.5
Gender: M
float CSE_marks;
Phone: 9940585840
char gender;
Name: Oshin
long int phone_no; ID: 4288
}; CSE Marks: 15.0
void main() Gender: F
Phone: 9119845321
{
struct student st1={“Rajkumar",1577,17.5,'M',9940585840};
struct student st2={"Oshin",4288,15,'F',9119845321};
printf ("Name: %s\n ID: %d\n CSE Marks: %.1f \nGender: %c
\nPhn: %d \
n",st1.name,st1.ID,st1.CSE_marks,st1.gender,st1.phone_no);
printf ("Name: %s\n ID: %d \nCSE Marks: %.1f \nGender: %c\n Phn: %d
\n",st2.name,st2.ID,st2.CSE_marks,st2.gender,st2.phone_no);
}
“Structure within another Structure
(Nested Structure)”
 Nested structure in C is nothing but structure within structure.
 One structure can be declared inside other structure as we declare structure
members inside a structure.
 The structure variables can be a normal structure variable or a pointer
variable to access the data.
 Nested Structures are allowed in C Programming Language.
 We can write one Structure inside another structure as member of another
structure.
Example:
struct dob
{
int dd;
Output:
int mm;
int yyyy;
VTUNO:1212
}; Name:Rajkumar
struct student1 DOB:6:12:2020
{ Department:CSE
int vtuno; --------------------------------
char name[30]; Process exited after 0.1409 seconds with return value 0
struct dob d;
Press any key to continue . . .
char dept;
}
int main()
{
struct dob d={6,12,2020};
struct student1 s3={1212,"Rajkumar",d,"CSE"};
printf("VTUNO:%d\nName:%s\nDOB:%d/%d/%d\nDepartment:
%s",s3.vtuno,s3.name,s3.d.dd,s3.d.mm,s3.d.yyyy,s3.dept);
}
struct Employee int main()
{ {
char ename[20];
struct Employee e;
scanf("%s",e.name);
int ssn;
scanf("%d",&e.ssn);
float salary; scanf("%f",&e.salary);
struct date scanf("%d",&e.doj.date);
{ scanf("%d",&e.doj.month);
scanf("%d",&e.doj.year);
int dd;
printf("Name:%s\nSSN:%d\nSalary:%.1f\nDOJ:%d:%d:
int mm; %d",e.name,e.ssn,e.salary,e.doj.date,e.doj.month,e.doj.year);
int yyyy; }
} doj;
};
Input: Output
Rajkumar Name:Rajkumar
1234 SSN:1234
50000 Salary:50000.0
29 DOJ:29:6:1975
6 --------------------------------
1975
Array of Structures
 An array is a collection of data items of the same type.
 Each element of the array can be int, char, float, double,
or even a structure.
 We have seen that a structure allows elements of
different data types to be grouped together under a single
name.
 This structure can then be thought of as a new data type
in itself.
 So, an array can comprise elements of this new data type.
 An array of structures finds its applications in grouping the
records together and provides for fast accessing.
void main()
{
struct student struct student s[10];
{ int i,n;
printf("\nEnter the no.of students:");
int regno; scanf("%d",&n);
char for(i=0;i<n;i++)
name[10],grade; {
printf("\nEnter the student regno,name,m1,m2,m3:");
int m1,m2,m3; scanf("%d%s%d%d
%d",&s[i].regno,&s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);
float avg,tot; s[i].tot=s[i].m1+s[i].m2+s[i].m3;
}; s[i].avg=s[i].tot/3;
if(s[i].m1<35||s[i].m2<35||s[i].m3<35)
s[i].grade='f';
else
{
if(s[i].avg>=75)
s[i].grade=‘A';
else if(s[i].avg>=60)
s[i].grade=‘B';
else if(s[i].avg>=50)
s[i].grade=‘C';
else if(s[i].avg>=35)
s[i].grade=‘D';
}
}
printf("\nSTUDENT MARK LIST\n");
printf("\nREGNO\tNAME\tTOTAL\tAvg\tGRADE");
for(i=0;i<n;i++)
printf("\n%d\t%s\t%f\t%f\t
%c",s[i].regno,s[i].name,s[i].tot,s[i].avg,s[i].grade);
getch();
}
Enter the no.of students:2
Enter the student regno,name,m1,m2,m3:101
John
89
98
78
Enter the student regno,name,m1,m2,m3:102
Chini
59
68
76
STUDENT MARK LIST

REGNO NAME TOTAL Avg GRADE


101 John 265.00 88.33 A
102 Chini 203.00 67.67 B
Union
 An Union is a collection of different data items,
that are stored under a common name. Here
same memory is shared by its members.
 Syntax:

union union _name


{
union element1;
union element2;
…………………
};
N.Rajkumar 14
 Example:
union result
{
int mark;
float avg;
char grade;

};
N.Rajkumar 15
// C Program to demonstrate how to union un var1;
use union
#include <stdio.h>
// initializing the union member
var1.member1 = 15;
// union template or declaration
union un {
printf("The value stored in
int member1; member1 = %d",
char member2; var1.member1);
float member3;
}; return 0;
}
// driver code
int main() OUTPUT
{ The value stored in member1 = 15

// defining a union variable


Example
#include<stdio.h>
#include<conio.h>
union stud
{
int a;
char b[2];
};
void main()
{
union stud c;

N.Rajkumar 17
c.a=256;
printf("\nc.a value is%d",c.a);
}

Output:
c.a value is256

N.Rajkumar 18
Structure and Union Difference

STRUCTURE UNION
The struct keyword is used to define a The union keyword is used to define
structure. union.
When the variables are declared in a When the variable is declared in the
structure, the compiler allocates memory to union, the compiler allocates memory to
each variables member. The size of a the largest size variable member. The
structure is equal or greater to the sum of the size of a union is equal to the size of its
sizes of each data member. largest data member size.

Each variable member occupied a unique Variables members share the memory
memory space. space of the largest size variable.

Changing the value of a member will not Changing the value of one member will
affect other variables members. also affect other variables members.

Each variable member will be assessed at a Only one variable member will be
time. assessed at a time.
We can initialize multiple variables of a In union, only the first data member can be
structure at a time. initialized.
Structure and Union Difference

STRUCTURE UNION
All variable members store some value at Exactly only one data member stores a
any point in the program. value at any particular instance in the
program.
The structure allows initializing multiple Union allows initializing only one
variable members at once. variable member at once.

It is used to store different data type values. It is used for storing one at a time from
different data type values.

It allows accessing and retrieving any data It allows accessing and retrieving any
member at a time. one data member at a time.
Size of Union

• The size of the union will always be equal to the size of the largest member of the array.
• All the less-sized elements can store the data in the same space without any overflow.

Union1&Union2
// C Program to find the size of the union
int arr[10];
#include <stdio.h> char y;
} Test3;
// declaring multiple unions
// driver code
union test1 {
int main()
int x;
{
int y; // finding size using sizeof() operator
} Test1; int size1 = sizeof(Test1);
int size2 = sizeof(Test2);
int size3 = sizeof(Test3);
union test2 {
int x;
printf("Sizeof test1: %d\n", size1);
char y; printf("Sizeof test2: %d\n", size2);
} Test2; printf("Sizeof test3: %d", size3);
return 0;
OUTPUT : }
union test3 { Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40
POINTERS
 Pointer is a variable that contains the memory address of another
variable.
 Every variable is a memory location and every memory location
has its address defined which can be accessed using ampersand
(&) operator.
 Advantages:
 It supports dynamic memory allocation and reallocation of
memory segments.
 Variables can be swapped without physically moving them
 It reduces the length and complexity of the program
Example
a=10

N.Rajkumar 24
Example
#include<stdio.h>
void main()
{
int a=5;
printf("\n The Address of a = %u",&a);
printf("\n The Value of a = %d",a);
}

Output
The Address of a = 8714
The Value of a = 5

N.Rajkumar 25
Pointer Declaration
• Syntax
data-type* pointer-name;

data-type - Type of the data to


which the pointer points.
pointer-name - Name of the pointer

• Example: int *a;


N.Rajkumar 26
int a=10;
int *ptr;
ptr=&a;

N.Rajkumar 27
void main()
{
int a=10;
int *p;
p=&a; //p=a its not possible
printf(“The address of a%d=”,&a);
printf(“The address of p=%d”,&p);
printf(“The value of a =%d”,a);
printf(“Actual value of p=%d”,p);
printf(“The value of p=%d”,*p);
}
Types of Pointers in C
pointers to primitive data types, pointers to user defined data types

 Integer Pointers----- int *ptr;


 Array Pointer------ char *ptr = &array_name;
 Structure Pointer---- struct struct_name *ptr;
 Function Pointers--- int (*ptr)(int, char);
 Double Pointers----- datatype ** pointer_name;
 *pointer_name; // get the address stored in the inner level pointer
 **pointer_name; // get the value pointed by inner level pointe
 NULL Pointer ---
data_type *pointer_name = NULL;
or
pointer_name = NULL
 Void Pointer
void * pointer_name;
 Constant Pointers
data_type * const pointer_name; (Address)
Pointer to Constant
const data_type * pointer_name; (value)
Other Types of Pointers in C:
 Far pointer: A far pointer is typically 32-bit that can access memory outside
the current segment.
 Dangling pointer: A pointer pointing to a memory location that has been
deleted (or freed) is called a dangling pointer.
 Huge pointer: A huge pointer is 32-bit long containing segment address and
offset address.
 Complex pointer: Pointers with multiple levels of indirection.
 Near pointer: Near pointer is used to store 16-bit addresses means within the
current segment on a 16-bit machine.
 Normalized pointer: It is a 32-bit pointer, which has as much of its value in
the segment register as possible.
 File Pointer: The pointer to a FILE data type is called a stream pointer or a
file pointer.
Size of Pointers in C
 The size of the pointers in C is equal for every pointer type.
 The size of the pointer does not depend on the type it is pointing to. It only
depends on the operating system and CPU architecture.

 The size of pointers in C is


 8 bytes for a 64-bit System
 4 bytes for a 32-bit System
C Program to find the size of different pointer types.
#include <stdio.h>
// printing sizes
printf("Size of Integer Pointer \t:\t%d bytes\n",
struct str {
sizeof(ptr_int));
};
printf("Size of Character Pointer\t:\t%d bytes\n",

// dummy function sizeof(ptr_char));


void func(int a, int b){}; printf("Size of Structure Pointer\t:\t%d bytes\n",
sizeof(ptr_str));
int main() printf("Size of Function Pointer\t:\t%d bytes\n",
{ sizeof(ptr_func));
// dummy variables definitions
printf("Size of NULL Void Pointer\t:\t%d bytes",
int a = 10;
sizeof(ptr_vn));
char c = 'G';
struct str x;
return 0;

// pointer definitions of different types } OUTPUT


int* ptr_int = &a; Size of Integer Pointer : 8 bytes
char* ptr_char = &c; Size of Character Pointer : 8 bytes
struct str* ptr_str = &x; Size of Structure Pointer : 8 bytes
void (*ptr_func)(int, int) = &func;
Size of Function Pointer : 8 bytes
void* ptr_vn = NULL;
Size of NULL Void Pointer : 8 bytes
POINTER ARITHMETIC
• Arithmetic operation supported pointers are
– Increment
– Decrement
– Adding integer value with pointer
– Subtracting integer value with pointer
• The following arithmetic operations are not
allowed with pointers
– Multiplication
– Division
– Add or subtract float/double with pointers…
N.Rajkumar 34
• Increment:
int x=10, *p;
p=&x;
p++;
• p++ will not add 1 to p, but add size of that
data type with p, which is pointed by the
pointer
• If p is 1000(Addr of x) after the statement
p=&x, then after p++, p will be 1004, because
the size of x is 4 bytes

N.Rajkumar 35
• Decrement:
int x, *p1,*p2,*p3;
p1=&x;
p2=p1--;
p3=p1--;
• p1-- will not decrement 1 to p1, but subtract
the size of that data type with p1, which is
pointed by the pointer
• If p1 is 1000(Addr of x) after the statement
p1=&x then:
• After the statement p2=p1--, p2=998
• After the statement p3=p1--, p3=996
N.Rajkumar 36
#include<stdio.h>
#include<conio.h> //Program to display the memory address
void main() of a variable using pointers, before and
after increment and decrement
{
int x=100;
int *ptr;
ptr=&x;
clrscr();
printf(“Address of x before increment = %u”,ptr);
ptr++;
printf (“Address of x after increment = %u”,ptr);
printf (“Address of x before decrement = %u”,ptr);
ptr--;
printf(“Address of x after decrement = %u”,ptr);
getch(); N.Rajkumar 37
• Adding integer value with pointer:
int *p,x;
x=10;
p=&x;
p=p+7;
• If p is 1000(Addr of x), then after the statement p=p+7, p will
be 1014.
• Subtracting integer value with pointer:
int *p,x;
x=10;
p=&x;
p=p-7;
• If p is 1000(Addr of x), then after the statement p=p-7, p will
be 986.

N.Rajkumar 38
#include<stdio.h>
//Program for adding and subtracting
#include<conio.h> integer value with pointer
void main()
{
int x, *p1, *p2, *p3;
x=20;
p1=&x;
p2=p1+7;
p3=p1-7;
printf(“Value of p1=%d”, *p1);
printf(“\nAddress of p1=%u”, p1);
printf(“\nAddress of p2=% u”, p2);
printf(“\nAddress of p3=% u”, p3);
getch();
} N.Rajkumar 39
Pointer to an Array
#include<stdio.h>
#include<string.h>
int main()
{
int a[5]={1,2,3,4,5};
int* p,i;
char *p1;
char name[]="Rajkumar";
p=&a;
p1=&name;
for(i=0;i<5;i++,p++)
printf("%d\n",*p);
for(i=0;i<strlen(name);i++,p1++)
printf("%c",*p1);
}
N.Rajkumar 40
#include<stdio.h>
int main()
{
int a[30];
int i,sum=0,*p,n;
printf("Enter the no of elements in array:");
scanf("%d",&n);
printf("Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
p=&a;
for(i=0;i<n;i++,p++)
sum=sum+*p;
printf("sum of array elements =%d ",sum);
}
N.Rajkumar 41
//Find Minimum and Maximum
#include<stdio.h>
int main()
{
int a[]={31,21,13,44,51,16,17,28};
int *p,i=30,max,min;
p=a;
max=min=*p;
printf("p=%d",p);
for(i=0;i<8;i++,p++)
{
if(*p>max)
max=*p;
if(*p<min)
min=*p;

}
printf("max=%d min=%d\n",&max,&min);
}

N.Rajkumar 42
//Find Minimum and Maximum
#include<stdio.h>
int main()
{
int a[]={31,21,13,44,51,16,17,28};
int *p,i=30,max,min;
p=a;
max=min=*p;
printf("p=%d",p);
for(i=0;i<8;i++,p++)
{
if(*p>max)
max=*p;
if(*p<min)
min=*p;

}
printf("max=%d min=%d\n",&max,&min);
}

N.Rajkumar 43
//Example for Pointer to structure

#include<stdio.h>
struct student
{
int vtuno;
char name[30];
};

int main()
{
struct student s[10];
struct student *p;
int i;
printf("Enter the student Details:");
for(i=0;i<3;i++)
{
printf("Enter the vtuno:");
scanf("%d",&s[i].vtuno);
printf("Enter the student name:");
scanf("%s",s[i].name);
}
p=&s;
for(i=0;i<3;i++,p++)
{
printf("%d\t%s\n",p->vtuno,p->name);
}
}

N.Rajkumar 44
Parameter Passing Methods
• Call by value
• Call by reference

N.Rajkumar 45
Call by value
• Actual argument passed to the formal argument.
• Any changes to the formal argument does not affect the actual
argument.

N.Rajkumar 46
Example
#include <stdio.h>
#include<conio.h>
int add(int,int);
int main()
{
int a,b,c;
clrscr();
printf("\nEnter two number:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("\nSum is:%d",c);
}
int add(int x,int y)
{
int z;
z=x+y;
x=x+20;
return(z);
}

N.Rajkumar 47
Output

Enter two number:6


7

Sum is:13

N.Rajkumar 48
Call by reference
• Instead of passing value, the address of the argument will be
passed.
• Any changes to the formal argument will affect the actual
argument.

N.Rajkumar 49
Example
#include <stdio.h> swap(&x,&y);
#include<conio.h> printf("\nx=%d,y=%d",x,y);
void swap(int*,int*); }
void main() void swap(int *a,int *b)
{ {
int x,y; int c;
c=*a;
printf("\nEnter value of x:"); *a=*b;
scanf("%d",&x); *b=c;
printf("\nEnter value of y:"); printf("\nx=%d,y=%d",*a,*b);
scanf("%d",&y); }
Output
Enter value of x:5
Enter value of y:6
x=6,y=5

N.Rajkumar 50
Dynamic Memory Allocation in C
• malloc()
• calloc()
• free()
• realloc()

N.Rajkumar 51
malloc()
• The “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size.
• It returns a pointer of type void which can be cast into a pointer of any form.
It doesn’t Initialize memory at execution time so that it has initialized each
block with the default garbage value initially.

Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example:

ptr = (int*) malloc(100 * sizeof(int));


N.Rajkumar 52

You might also like