Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

CS4206 Commonto CSE,IT, ADS ProgramminginC

UNIT-IV
STRUCTURESStructure-Nestedstructures–PointerandStructures–Arrayofstructures–
ExampleProgramusingstructuresandpointers–Selfreferentialstructures–
Dynamicmemoryallocation-typedef

4.1 Structure
Arraysallowtodefinetypeofvariablesthatcanholdseveraldataitemsofthesamekind.Si
milarlystructureisanotheruserdefineddatatypeavailableinCthatallowstocombined
ataitemsofdifferentkinds.
Structures are used to represent a record. Suppose you want to keep track of
yourbooksinalibrary.Youmightwanttotrackthefollowingattributesabouteachbook

 Title
 Author
 Subject
 BookID
DefiningaStructure
Todefineastructure,youmustusethe struct
statement.Thestructstatementdefinesanewdatatype,withmorethanonemember.Thefor
matofthestructstatementisasfollows−
struct[structuretag]{

memberdefinition;member
definition;
...
memberdefinition;
}[oneormorestructurevariables];
Thestructuretagisoptionalandeachmemberdefinitionisanormalvariable
definition, such as int i; or float f; or any other valid variable definition. At the
endofthestructure'sdefinition,beforethefinalsemicolon,youcanspecifyoneormorest
ructure variables but it is optional. Here is the way you would declare the
Bookstructure−
structBooks
{chartitle[50];ch
arauthor[50];
charsubject[100];i
ntbook_id;
}book;
AccessingStructureMembers
To access any member of a structure, we use the member access operator (.).
Thememberaccess operatoris coded asaperiodbetweenthestructure
variablenameandthestructurememberthat we wish to access. You would use
thekeyword struct
todefinevariablesofstructuretype.Thefollowingexampleshowshowtouseastructureinap
rogram−
#include<stdio.h>
#include<string.h>

structBooks{ch
artitle[50];

St.Joseph’s Institute of Technology 1


CS4206 Commonto CSE,IT, ADS ProgramminginC

charauthor[50];charsubject[100];intbook_id;
};

intmain(){

structBooksBook1;structBooksBook2;

/*DeclareBook1oftypeBook*/
/*DeclareBook2oftypeBook*/

/*book1specification*/
strcpy(Book1.title,"CProgramming");strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");Book1.book_id=6495407;

/*book2specification*/
strcpy(Book2.title,"TelecomBilling");strcpy(Book2.author,"ZaraAli");
strcpy( Book2.subject,"Telecom BillingTutorial");Book2.book_id=6495700;

/*printBook1info*/
printf("Book1title:%s\n",Book1.title);printf("Book1author:%s\n",Book1.author);printf("Book1sub
printf("Book1book_id:%d\n",Book1.book_id);

/*printBook2info*/
printf("Book2title:%s\n",Book2.title);printf("Book2author:%s\n",Book2.author);printf("Book2sub
printf("Book2book_id:%d\n",Book2.book_id);

return0;

}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult−
Book1title:CProgrammingB
ook1author:NuhaAli
Book1subject:CProgrammingTutorialBo
ok1book_id :6495407
Book2title:TelecomBillingBoo
k2author:ZaraAli
Book2subject:TelecomBillingTutorialBoo
k2book_id:6495700
4.2 NestedStructure
When a structure contains anotherstructure, itis called nested structure.
Forexample,we have two structures named Address and Employee. To make
AddressnestedtoEmployee,wehavetodefineAddressstructurebeforeandoutside

St.Joseph’s Institute of Technology 2


CS4206 Commonto CSE,IT, ADS ProgramminginC

EmployeestructureandcreateanobjectofAddressstructureinsideEmployeestructure.
Syntaxforstructurewithinstructureornestedstructure

structstructure1
{
----------
----------
};

structstructure2
{
----------
----------
struct structure1obj;
};

Exampleforstructurewithinstructureornestedstructure

#include<stdio.h>

structAddress
{
charHouseNo[25];char
City[25];
charPinCode[25];
};

structEmployee
{
int Id;
charName[25];fl
oatSalary;
structAddressAdd;
};

voidmain()
{
inti;
structEmployeeE;

printf("\n\
tEnterEmployeeId:");scanf("%d",&E.Id);

printf("\n\
tEnterEmployeeName:");scanf("%s",&E.Na
me);

printf("\n\
tEnterEmployeeSalary:");scanf("%f",&E.Sal

St.Joseph’s Institute of Technology 3


CS4206 Commonto CSE,IT, ADS ProgramminginC

printf("\n\
tEnterEmployeeHouseNo:");scanf("%s",&
E.Add.HouseNo);

printf("\n\
tEnterEmployeeCity:");scanf("%s",
&E.Add.City);

printf("\n\
tEnterEmployeeHouseNo:");scanf("%s",&
E.Add.PinCode);

printf("\nDetailsofEmployees");printf("\n\
tEmployeeId:%d",E.Id);printf("\n\
tEmployee Name : %s",E.Name);printf("\n\
tEmployeeSalary:%f",E.Salary);
printf("\n\tEmployeeHouseNo:%s",E.Add.HouseNo);printf("\n\
tEmployeeCity:%s",E.Add.City);printf("\n\tEmployeeHouseNo:
%s",E.Add.PinCode);
}

Output:

EnterEmployeeId:101
EnterEmployeeName:SureshEnterE
mployeeSalary:45000EnterEmploye
eHouseNo:4598/
DEnterEmployeeCity:Delhi
EnterEmployeePinCode:110056

DetailsofEmployeesEmployee
Id:101EmployeeName:Su
reshEmployeeSalary:450
00
EmployeeHouseNo:4598/

4.3 PointerandStructures

Structures
canbecreatedandaccessedusingpointers.Apointervariableofastructurecanbecreatedasbe
low:
St.Joseph’s Institute of Technology 4
CS4206 Commonto CSE,IT, ADS ProgramminginC

structname{
member1;
member2;
.
.
};

intmain()
{
structname*ptr;
}

Here,thepointervariableoftypestructnameiscreated.
Accessingstructure'smemberthroughpointer
Astructure'smembercanbeaccesssedthroughpointerintwoways:
1. Referencingpointertoanotheraddresstoaccessmemory
2. Usingdynamicmemoryallocation
1. Referencingpointertoanotheraddresstoaccessthememory
Consideranexampletoaccessstructure'smemberthroughpointer.
#include<stdio.h>typ
edefstructperson
{
intage;
floatweight;
};

intmain()
{
structperson*personPtr,person1;
personPtr=&person1;

//Referencingpointertomemoryaddressofperson1

printf("Enterinteger:");scanf("%d",&(*personPtr).age);

printf("Enternumber:");scanf("%f",&(*personPtr).weig
ht);

printf("Displaying:");printf("%d%f",(*personPtr).age,
(*personPtr).weight);

return0;
}
Inthisexample,thepointervariableoftype structperson isreferencedtotheaddressof
person1.Then,onlythestructurememberthroughpointercancanaccessed.
Using->operatortoaccessstructurepointermember
Structurepointermembercanalsobeaccessedusing->operator.

(*personPtr).ageissameaspersonPtr->age

St.Joseph’s Institute of Technology 5


CS4206 Commonto CSE,IT, ADS ProgramminginC

(*personPtr).weightissameaspersonPtr->weight

2. Accessingstructurememberthroughpointerusingdynamicmemoryallocation
Toaccessstructurememberusingpointers,memorycanbeallocateddynamicallyusing
malloc()functiondefinedunder"stdlib.h"headerfile.
Syntaxtousemalloc()

ptr=(cast-type*)malloc(byte-size)

Exampletousestructure'smemberthroughpointerusingmalloc()function.
#include <stdio.h>#include <stdlib.h>structperson{
intage;
float weight;charname[30];
};

intmain()
{
structperson*ptr;inti,num;

printf("Enternumberofpersons:");scanf("%d",&num);

ptr=(structperson*)malloc(num*sizeof(structperson));
//Abovestatement allocatesthememory fornstructureswithpointerpersonPtrpointingtobaseaddress*/

for(i=0;i<num;++i)
{
printf("Enter name, age and weight of the person respectively:\n");scanf("%s%d%f",&(ptr+i)->name,&
}

printf("DisplayingInfromation:\n");for(i=0;i<num;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->name,(ptr+i)->age,(ptr+i)->weight);

return0;
}

Output

Enternumberofpersons:2
Entername,ageandweightofthepersonrespectively:Ad
am
2
3.2
Entername,ageandweightofthepersonrespectively:

St.Joseph’s Institute of Technology 6


CS4206 Commonto CSE,IT, ADS ProgramminginC

Eve
6
2.3
DisplayingInformation:A
dam 2 3.20
Eve 6 2.30

4.4 ArrayofStructure
StructureisusedtostoretheinformationofOneparticularobjectbutifweneedtostoresuch10
0objectsthen Array ofStructureis used.
Example:
structBookinfo
{
char[20]bname;intpages;
intprice;
}Book[100];

Explanation:
1. HereBookstructureisusedtoStoretheinformationofoneBook.
2. IncaseifweneedtostoretheInformationof100booksthenArrayofStructureisuse
d.
3. b1[0] stores the Information of 1st Book , b1[1] stores the information of
2ndBook and So onWecan storethe informationof100books.
ExampleProgramForArrayOfStructuresInC:
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
manystudents. You can store “n” number of students record by declaring
structurevariableas‘structstudentrecord[n]“,wherencanbe1000or5000etc.
Program:
#include<stdio.h>
#include<string.h>

structstudent
{
intid;
charname[30];float
percentage;
};

intmain()
{
inti;
structstudentrecord[2];

//1ststudent's
recordrecord[0].id=1;strcpy(record[0
].name,"Raju");record[0].percentage=
86.5;

St.Joseph’s Institute of Technology 7


CS4206 Commonto CSE,IT, ADS ProgramminginC

//
2ndstudent'srecordrecord[1].id=2;st
rcpy(record[1].name,"Surendren");rec
ord[1].percentage=90.5;

//
3rdstudent'srecordrecord[2].id=3;st
rcpy(record[2].name,"Thiyagu");recor
d[2].percentage=81.5;

for(i=0;i<3;i++)
{
printf(" RecordsofSTUDENT:%d\
n",i+1);printf("Idis:%d\n",record[i].id);
printf("Nameis:%s\n",record[i].name);
printf("Percentageis:%f\n\n",record[i].percentage);
}
return0;
}
OUTPUT:
RecordsIdNameof STUDENT : 1
is: 1
is: Raju
Percentageis:86.500000
Recordsof STUDENT : 2
IdName is: 2
is: Surendren
Percentageis:90.500000
RecordsofSTUDENT:3
Idis:3
Nameis:ThiyaguPercentageis:81.500000

ExampleProgramForDeclaringManyStructureVariableInC:
In this program, two structure variables “record1″ and“record2″aredeclaredforsame structure and di

Program:
#include<stdio.h>
#include<string.h>

structstudent
{
intid;
charname[30];float
percentage;
};

intmain()
{
inti;

St.Joseph’s Institute of Technology 8


CS4206 Commonto CSE,IT, ADS ProgramminginC

structstudentrecord1={1,"Raju",90.5};stru
ctstudentrecord2={2,"Mani",93.5};

printf("RecordsofSTUDENT1:\
n");printf("Idis:%d\
n",record1.id);printf("Nameis:%s\
n",record1.name);
printf("Percentageis:%f\n\n",record1.percentage);

printf("RecordsofSTUDENT2:\
n");printf("Idis:%d\
n",record2.id);printf("Nameis:%s\
n",record2.name);
printf("Percentageis:%f\n\n",record2.percentage);

return0;
}
OUTPUT:
RecordsIdName
of STUDENT1:
PercentageRecordsId
is: 1
Name
is: Raju90.500000STUDENT2:
is: 2
of Mani
is:
is:
Percentageis:93.500000

4.5 ExampleProgramusingstructuresandpointers
ExampleProgramForCStructureUsingPointer:
Inthisprogram,“record1”isnormalstructurevariableand“ptr”ispointerstructurevariable. As you know,

Program:
#include<stdio.h>
#include<string.h>

structstudent
{
intid;
charname[30];float
percentage;
};

intmain()
{
inti;
structstudentrecord1={1,"Raju",90.5};str
uctstudent*ptr;

ptr=&record1;
St.Joseph’s Institute of Technology 9
CS4206 Commonto CSE,IT, ADS ProgramminginC

printf("RecordsofSTUDENT1:\
n");printf("Idis:%d\n",ptr-
>id);printf("Nameis:%s\n",ptr-
>name);
printf("Percentageis:%f\n\n",ptr->percentage);

return0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is:

RajuPercentageis:90.500000

ExampleProgramToCopyAStructureInC:
TherearemanymethodstocopyonestructuretoanotherstructureinC.
1. Wecancopyusingdirectassignmentofonestructuretoanotherstructureor
2. wecanuseCinbuiltfunction“memcpy()”or
3. wecancopybyindividualstructuremembers.

Program:

4. #include<stdio.h>
5. #include
<string.h>6.
7.struct
student8.{
9. int id;
10. charname[30];
11. floatpercentage;
12.};
13.
14.intmain()
15.{
16. inti;
17. structstudentrecord1={1,"Raju",90.5};
18. structstudentrecord2,*record3,*ptr1,record4;19
.
20. printf("RecordsofSTUDENT1-record1structure\n");
21. printf("Id:%d\nName:%s\nPercentage:%f\n",
22. record1.id,record1.name,record1.percentage);2
3.
24. //1stmethodtocopywholestructuretoanotherstructure
25. record2=record1;
26.
27. printf("\nRecordsofSTUDENT1-Directcopyfrom"\
28. "record1\n");
29. printf("Id:%d\nName:%s\nPercentage:%f\n",
30. record2.id,record2.name,record2.percentage);3
1.
St.Joseph’s Institute of Technology 10
CS4206 Commonto CSE,IT, ADS ProgramminginC

32. //2ndmethodtocopyusingmemcpyfunction
33. ptr1=&record1;
34. memcpy(record3,ptr1,sizeof(record1));3
5.
36. printf("\nRecordsofSTUDENT1 -copiedfromrecord1"\
37. "usingmemcpy \n");
38. printf("Id:%d\nName:%s\nPercentage:%f\n",
39. record3->id,record3->name,record3-
>percentage);40.
41. //3rdmethodtocopybyindividualmembers
42. printf("\nRecordsofSTUDENT1-Copiedindividual"\
43. "membersfromrecord1\n");
44. record4.id=record1.id;
45. strcpy(record4.name,record1.name);
46. record4.percentage=record1.percentage;4
7.
48. printf("Id:%d\nName:%s\nPercentage:%f\n",
49. record4.id,record4.name,record4.percentage);5
0.
51. return0;
52.}
OUTPUT:
Records of STUDENT1 –record1 structure
Id : 1
Name : Raju
Percentage : 90.500000
RecordsofSTUDENT1–Directcopyfromrecord1
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1–
copiedfromrecord1usingmemcpy
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 –Copied
individualmembers
from record1
Id : 1
Name :
4.6 Selfreferentialstructures
Considerthestructuredeclarationbelow,
structNODE{
structNODEnew;

/*'new'declaredvariable*/intvalue;
};
Asweknowthatstructuretemplatetellscompilerhowtoallocatestoragetoits
membersandmakescomputernottoallocatememorytothem.Whencompilerreachesth
eline
structNODEnew;

St.Joseph’s Institute of Technology 11


CS4206 Commonto CSE,IT, ADS ProgramminginC

templatestructNODEisnotfullydefined.Further,its member‘new’of
typestructNODEcontainsamember‘new’oftypestructNODEwhichinturncontainsamembe
r ‘new’ again of type struct NODE and so on indefinitely. In such an instance,compiler
can’t evaluate correctly how much storage to allocate to ‘new’ member
oftemplatestructNODE.SoweobservedherethatamemberofstructNODEcan’tbea variable
of type struct NODE. Then, how can we make structure struct NODE self-referential?
Let’stakeonemoretry,thistimewedeclarea‘pointer-to-structNODE’
as amemberoftemplatestructNODE,
structNODE{
structNODE*new;

/*'new'apointer-to-structNODE*/intvalue;
};
AscompilerstartscompilingthetemplatestructNODEandreachesline
structNODE*new;
itfinds‘new’,a‘pointer-to-
structNODE’,andalsomemberofstructNODEtemplate,itevaluatescorrectlyhowmuchbytes
ofstoragetobeallocated to‘new’.
Onlinuxsystem,anypointertypetakes8bytesofstorage.
There’snoprobleminusing‘pointer-to-
structNODE’asamemberofstructNODE.Because‘new’isa‘pointer-to-
structNODE’,structurestructNODEiscalledself-referential
structure.
typedefstructNODE{
structNODE*new;i
ntvalue;
}Node;

intmain(void)
{
Nodeprevious,current;

/*accessingmembersof'previous'*/
previous.new=&current;
/* previous.new is a 'pointer-to-struct NODE'
*/previous.value=100;
}

4.7 DynamicMemoryAllocation
The C programming language manages memory statically, automatically,or
dynamically.Staticvariablesareallocatedinmainmemory,usuallyalongwiththe
executable code of the program, and persist for the lifetime of the
program;automatic variables are allocated on the stack and come and go as
functions arecalled and return. For static and automatic variables, the size of the
allocation mustbecompile-timeconstant(exceptforthecaseofvariable-
lengthautomaticarrays).Iftherequiredsizeisnotknownuntilrun-time(for
example,ifdataofarbitrarysizeisbeing read from the user or from a disk file), then
using fixed-size data objects isinadequate.
Thelifetimeofallocatedmemorycanalsocauseconcern.Neitherstatic-norautomatic
memory is adequate for all situations. Automatic-allocated data
cannotpersistacrossmultiplefunctioncalls,whilestaticdatapersistsforthelifeofthe
St.Joseph’s Institute of Technology 12
CS4206 Commonto CSE,IT, ADS ProgramminginC

programwhetheritisneededornot.Inmanysituationstheprogrammerrequiresgreaterflexi
bilityinmanagingthelifetimeofallocatedmemory.
Theselimitationsareavoidedbyusingdynamicmemoryallocationinwhichmemoryismoree
xplicitlyandmoreflexiblymanaged,typically,byallocatingit
fromthefreestore(informallycalledthe"heap").InC,thelibraryfunction mallo is
usedtoallocateablockofmemoryontheheap.Theprogramaccessesthisblockof c
memoryviaapointer malloc returns.Whenthememoryisnolongerneeded,whichdea
thatthepointeris free llocatesthememorysothatitcanbeusedfor
passedtootherpurposes.
Someplatformsprovidelibrarycallswhichallowrun-timedynamicallocationfrom
theCstackratherthantheheap(e.g.alloca()).Thismemoryisautomaticallyfreedwhenthecall
ingfunctionends.

Dynamicmemoryallocationallowsyourprogramtoobtainmorememoryspacewhile
running,ortoreleaseitif it'snotrequired.Insimpleterms,Dynamicmemory
allocation allows you to manually handle memory space for your
program.InCthereare4libraryfunctionsunder"stdlib.h"fordynamicmemoryallocation
.

Function UseofFunction

Allocatesrequestedsizeofbytesandreturnsapointerfirstbyteofallocatedspa
malloc()
ce

Allocatesspaceforanarrayelements,initializestozeroandthenreturnsapointert
calloc()
omemory

free() deallocatethepreviouslyallocatedspace

realloc() Changethesizeofpreviouslyallocatedspace

malloc()
Thenamemallocstandsfor"memoryallocation".
Thefunctionmalloc()reservesablockofmemoryofspecifiedsizeandreturnapointeroftypev
oidwhichcanbecastedintopointerofanyform.
Syntaxofmalloc()
ptr=(cast-type*)malloc(byte-size)

Here,ptrispointerofcast-
type.Themalloc()functionreturnsapointertoanareaofmemory with size of byte size.
If the space is insufficient, allocation fails and returnsNULLpointer.
Example:

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

Thisstatementwillallocateeither200or400accordingtosizeofint2or4bytes
respectivelyandthepointerpointstotheaddressoffirstbyteofmemory.
calloc()
Thenamecallocstandsfor"contiguousallocation".

St.Joseph’s Institute of Technology 13


CS4206 Commonto CSE,IT, ADS ProgramminginC

The only difference between malloc() and calloc() is that, malloc() allocates
singleblock of memory whereas calloc() allocates multiple blocks of memory each
of samesizeandsetsallbytestozero.
Syntaxofcalloc()

ptr=(cast-type*)calloc(n,element-size);

Thisstatementwillallocatecontiguousspaceinmemoryforanarrayofnelements.
Forexample:

ptr=(float*)calloc(25,sizeof(float));

Thisstatementallocatescontiguousspaceinmemoryforanarrayof25elements
eachofsizeoffloat,i.e,4bytes.
free()
Dynamicallyallocatedmemorycreatedwitheithercalloc()ormalloc()doesn'tgetfreed
onitsown.Youmust explicitlyusefree()toreleasethe space.
syntaxoffree()

free(ptr);

Thisstatementfreesthespaceallocatedinthememorypointedbyptr.
Example:ForCmalloc()andfree()S
umofElementinanarray

#include<stdio.h>
#include<stdlib.h>

intmain()
{
int num, i, *ptr,sum= 0;

printf("EnternumberofelementsintheArray:");scanf("%
d",&num);

ptr=(int*)malloc(num*sizeof(int));if(
ptr==NULL)
{
printf("Error!
Unabletoallocatememory.");exit(0);
}

printf("Enterelementsofarray:");fo
r(i=0;i<num;++i)
{
scanf("%d",ptr+i);
}
for(i=0;i<num;++i)
{
sum+=*(ptr+i);
}

St.Joseph’s Institute of Technology 14


CS4206 Commonto CSE,IT, ADS ProgramminginC

printf("SumofElementsinthegivenarrayis:%d",sum);free(ptr);
return0;
}

Output:

Herenumberofelementinthearrayisreadfromuserattheruntime.Arrayofsizenisallocat
edinmemoryusingmalloc()function.
Example:forCcalloc()andfree()S
umofElementinanarray

#include<stdio.h>
#include<stdlib.h>

intmain()
{
int num, i, *ptr,sum= 0;

printf("EnternumberofelementsintheArray:");scanf("%
d",&num);

ptr=(int*)calloc(num,sizeof(int));if(
ptr==NULL)
{
printf("Error!
Unabletoallocatememory.");exit(0);
}

printf("Enterelementsofarray:");fo
r(i=0;i<num;++i)
{
scanf("%d",ptr+i);
}
for(i=0;i<num;++i)
{
sum+=*(ptr+i);
}

printf("SumofElementsinthegivenarrayis:%d",sum);free(ptr);
return0;
}

Output:

St.Joseph’s Institute of Technology 15


CS4206 Commonto CSE,IT, ADS ProgramminginC

Aboveprogramalsodothesameprocessthatwasperformedinpreviousprogram.Onlydiffere
nsisinsteadofusingmalloc()functionherecalloc()functionisused.

realloc()
Ifthepreviouslyallocatedmemoryisinsufficientormorethanrequired,youcanchangethepr
eviously allocatedmemorysize usingrealloc().
Syntaxofrealloc()

ptr=realloc(ptr,newsize);

Here,ptrisreallocatedwithsizeofnewsize.
Example:forrealloc()

#include<stdio.h>
#include<stdlib.h>

intmain()
{
intnum, num2,i,*ptr, sum= 0;

printf("EnternumberofelementsintheArray:");scanf("%
d",&num);

ptr=(int*)calloc(num,sizeof(int));if(
ptr==NULL)
{
printf("Error!
Unabletoallocatememory.");exit(0);
}

printf("Enterelementsofarray:");fo
r(i=0;i<num;++i)
{
scanf("%d",ptr+i);
}
for(i=0;i<num;++i)
{
sum+=*(ptr+i);
}

printf("SumofElementsinthegivenarrayis:%d",sum);printf("\
nWanttoaddmoreelementinarray!");printf("\
nEnternumberofNewelementsintheArray:");scanf("%d",&num2
);

ptr=realloc(ptr,num2);if
(ptr==NULL)

St.Joseph’s Institute of Technology 16


CS4206 Commonto CSE,IT, ADS ProgramminginC

{
printf("Error!Unabletoallocatememory.");exit(0);
}

printf("\
nEnterNewelementsofarray:");for(i=num;i<nu
m+num2;++i)
{
scanf("%d",ptr+i);
}
sum=0;
for(i=0;i<num+num2;++i)
{
sum+=*(ptr+i);
}
printf("\nSum of all Elements in the given array is : %d",
sum);free(ptr);
return0;
}

Output:

Hererealloc()functionisusedtoreallocatethesizeofthearray,thatwascr
eatedusingcalloc()functiontoaddextraelementsinthearray.

4.8 Typedef
typedef is a keyword used in C language to assign alternative names to
existingtypes. Its mostly used with user defined data types, when names of data
types getslightlycomplicated.Followingisthegeneral syntaxforusingtypedef,
typedefexisting_namealias_name
Letstakeanexampleandseehowtypedefactuallyworks.
typedefunsignedlongulong;
The above statement define a termulongfor an unsigned long type.
Nowthisulongidentifiercanbeusedtodefine unsignedlongtypevariables.
ulongi,j;

typedefinuserdefineddatatype
typedefcanbeusedtogiveanametouserdefineddatatypeaswell.Letsseeitsusewithstructur
es.

St.Joseph’s Institute of Technology 17


CS4206 Commonto CSE,IT, ADS ProgramminginC

typedefstruct
{
type
member1;type
member2;type
member3;
Heretype_namerepresents
}type_name; the stucture definition associated with it. Now
thistype_namecanbeusedtodeclareavariableofthisstucturetype.
type_namet1,t2;

Example:#include
<stdio.h>#include
<conio.h>#include
<string.h>

typedefstructstudent
{
charname[50];i
ntmark;
}stud;

voidmain()
{
studs;
printf("\nEnterStudentDetail\
n");printf("\nStudentname\
t");scanf("%s",s.name);printf("\
nEnterStudentMark\
t");scanf("%d",&s.mark);
printf("\nStudentnameis:%s",s.name);printf("\
nStudentMarkis:%d",s.mark);
getch();
}
Output:

typedefandPointers
typedef can be used to give an alias name to pointers also. Here we have a case
inwhichuseoftypedefisbeneficialduringpointerdeclaration.
InPointers*bindstotherightandnottheleft.
int*x,y;
Bythisdeclarationstatement,weareactuallydeclaring x
asapointeroftypeint,whereasywillbedeclaredasaplaininteger.
typedefint*IntPtr;
IntPtrx,y,z;
Butifweusetypedeflikeinaboveexample,wecandeclareanynumberofpointers
inasinglestatement.

St.Joseph’s Institute of Technology 18

You might also like