24
Dale Roberts Department of Computer and Information Science, Department of Computer and Information Science, School of Science, IUPUI School of Science, IUPUI CSCI 230 Structures Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected]

Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected]

  • Upload
    tass

  • View
    41

  • Download
    0

Embed Size (px)

DESCRIPTION

Department of Computer and Information Science, School of Science, IUPUI. CSCI 230. Structures. Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected]. Introduction. Structures - PowerPoint PPT Presentation

Citation preview

Page 1: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Department of Computer and Information Science,Department of Computer and Information Science,School of Science, IUPUISchool of Science, IUPUI

CSCI 230

Structures

Dale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected]

Page 2: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

IntroductionIntroduction

StructuresStructuresA collection of one or more variables, possibly of different types, A collection of one or more variables, possibly of different types, grouped together under a single name for continent handling.grouped together under a single name for continent handling.

Commonly used to define records to be stored in filesCommonly used to define records to be stored in files

Combined with pointers, can create linked lists, stacks, queues, and Combined with pointers, can create linked lists, stacks, queues, and treestrees

Example:Example:struct card {struct card {

char *face;char *face; char *suit;char *suit; }; };

structstruct introduces the definition for structure card introduces the definition for structure card

cardcard is the structure name and is used to declare variables of the is the structure name and is used to declare variables of the structure type structure type

cardcard contains two members of type contains two members of type char *char *

These members are These members are faceface and and suitsuit

Page 3: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Structure DefinitionsStructure DefinitionsExampleExample: :

A date consists of several parts, such as the day, month, and year, and the day of the A date consists of several parts, such as the day, month, and year, and the day of the year, and the month nameyear, and the month name

structstruct date { date {int day;int day;int month;int month;int year;int year;int year_date;int year_date;char month_name[4];char month_name[4];};};

datedate: the name of the structure, called : the name of the structure, called structure tagstructure tag.. dayday, , monthmonth, …: the elements or variables mentioned in a structure , …: the elements or variables mentioned in a structure are called are called membersmembers..

structstruct information informationA A structstruct cannot contain an instance of itself cannot contain an instance of itselfCan contain a member that is a pointer to the same structure typeCan contain a member that is a pointer to the same structure typeA structure definition does not reserve space in memory A structure definition does not reserve space in memory

Instead creates a new data type used to declare structure variablesInstead creates a new data type used to declare structure variables

Page 4: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Declaration of Variables of StructureDeclaration of Variables of Structure

DeclarationsDeclarationsmethod 1method 1:: declared like other variables: declare tag first, and then declared like other variables: declare tag first, and then

declare variable.declare variable.struct card {struct card {

char *face;char *face;char *suit;char *suit;

};};struct card oneCard, deck[ 52 ],struct card oneCard, deck[ 52 ],

*cPtr;*cPtr;

method 2method 2:: A list of variables can be declared after the right brace and A list of variables can be declared after the right brace and use comma separated list:use comma separated list:

struct card {struct card {char *face;char *face;char *suit;char *suit;

} oneCard, deck[ 52 ], *cPtr;} oneCard, deck[ 52 ], *cPtr;

method 3method 3:: Declare only variables.Declare only variables.

struct {struct {char *face;char *face;char *suit;char *suit;

} oneCard, deck[ 52 ], *cPtr;} oneCard, deck[ 52 ], *cPtr;

struct date {.. .. ..

};struct date d1, d2, d3, d4, d5;

struct date { .. .. ..} d1, d2, d3;struct date d4, d5;

struct { .. .. ..} d1, d2, d3, d4, d5;

Page 5: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Structure DefinitionsStructure Definitions

Valid OperationsValid OperationsAssigning a structure to a structure of the same type Assigning a structure to a structure of the same type

Taking the address (Taking the address (&&) of a structure ) of a structure

Accessing the members of a structure Accessing the members of a structure

Using the Using the sizeofsizeof operator to determine the size of a structure operator to determine the size of a structure

Initialization of StructuresInitialization of StructuresInitializer listsInitializer lists

ExampleExample::

struct card oneCard = { "Three", "Hearts" };struct card oneCard = { "Three", "Hearts" };

ExampleExample::struct date d1 = {4, 7, 1776, 186, “Jul”};struct date d1 = {4, 7, 1776, 186, “Jul”};struct date d2 = {4, 7, 1776, 186, {‘J’,’u’,’l’,’\0’}};struct date d2 = {4, 7, 1776, 186, {‘J’,’u’,’l’,’\0’}};

Assignment statementsAssignment statementsExampleExample::

card threeHearts = oneCard;card threeHearts = oneCard;

Page 6: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Accessing Members of StructuresAccessing Members of Structures

Accessing structure membersAccessing structure membersDot (Dot (..) is a member operator used with structure ) is a member operator used with structure variablesvariables

Syntax: Syntax: structure_name. memberstructure_name. member struct card myCard;struct card myCard; printf( "%s", myCard.suit );printf( "%s", myCard.suit );

One could also declare and initialize One could also declare and initialize threeHeartsthreeHearts as follows: as follows:struct card threeHearts;struct card threeHearts;threeHearts.face = “Three”;threeHearts.face = “Three”;threeHearts.suit = “Hearts”;threeHearts.suit = “Hearts”;

Arrow operator (Arrow operator (->->) used with pointers to structure ) used with pointers to structure variablesvariables

struct card *myCardPtr = &myCard;struct card *myCardPtr = &myCard;printf( "%s", myCardPtr->suit );printf( "%s", myCardPtr->suit );

myCardPtr->suitmyCardPtr->suit is equivalent to is equivalent to (*myCardPtr).suit(*myCardPtr).suit

Page 7: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

StructuresStructures

Structure can be nestedStructure can be nestedstructstruct date { date {

int day;int day;int month;int month;int year;int year;int year_date;int year_date;char month_name[4];char month_name[4];};};

struct person {struct person {char name [NAME_LEN];char name [NAME_LEN];char address[ADDR_LEN};char address[ADDR_LEN};long zipcode;long zipcode;long ss__number;long ss__number;double salary;double salary;

struct date birthday;struct date birthday;};};

struct person emp;struct person emp;

emp.birthday.month = 6;emp.birthday.month = 6;emp.birthday.year = 1776;emp.birthday.year = 1776;

• Name Rule• Members in different structure

can have the same name, since they are at different position.

struct s1 {.. .. .. ..char name[10];.. .. .. ..} d1;

struct s2 {.. .. .. ..

int name;.. .. .. ..} d2;

struct s3 {.. .. .. ..

int name;

struct s3 t3; /* name */.. .. .. ..

} d2;

float name;

Page 8: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Memory LayoutMemory Layout

ExampleExample:: struct data1 {struct data1 {int day1;int day1;char month[9];char month[9];int year;int year;

};};Word (2 bytes) alignment machine – begins (aligns)Word (2 bytes) alignment machine – begins (aligns)at even address, such as PC, SUN workstationat even address, such as PC, SUN workstation

day1day1 intint 2 bytes2 bytesmonthmonth char arraychar array 9 bytes9 bytes(hole)(hole) 1 bytes1 bytesyearyear int int 2 bytes2 bytes

Quad (4 bytes) address alignment – begins (aligns)Quad (4 bytes) address alignment – begins (aligns)at quad address, such as VAX 8200at quad address, such as VAX 8200day1day1 intint 4 bytes4 bytesmonthmonth char arraychar array 9 bytes9 bytes(hole)(hole) 3 bytes3 bytesyearyear int int 4 bytes4 bytes

You must take care of You must take care of holehole, if you want to access data from very low level (i.e. , if you want to access data from very low level (i.e. low-level I/O, byte operations, etc.)low-level I/O, byte operations, etc.)

0

1

2 - 10

11

12

13

integer

integer

9 character

(hole)

0 - 3

4 - 12

13 - 15

16-19

integer

integer

9 character

(hole)

Page 9: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

sizeof sizeof OperatorOperator

sizeof(struct tag)sizeof(struct tag)

struct test {struct test {char name[5];char name[5];int i;int i; /* assume int is 2 bytes *//* assume int is 2 bytes */char s;char s;

} t1, t2;} t1, t2;

main()main(){{

printf(“sizeof(struct test) = %d\n”, sizeof (struct test));printf(“sizeof(struct test) = %d\n”, sizeof (struct test));printf(“address of t1 = %d\n”, &t1);printf(“address of t1 = %d\n”, &t1);printf(“address of t2 = %d\n”, &t2);printf(“address of t2 = %d\n”, &t2);printf(“address of t1.name = %d\n”, t1.name);printf(“address of t1.name = %d\n”, t1.name);printf(“address of t1.i = %d\n”, &t1.i);printf(“address of t1.i = %d\n”, &t1.i);printf(“address of t1.s = %d\n”, &t1.s);printf(“address of t1.s = %d\n”, &t1.s);

}}

output:output:

sizeof(struct test) = 10sizeof(struct test) = 10address of t1 = 992address of t1 = 992address of t2 = 1002address of t2 = 1002address of t1.name = 992address of t1.name = 992address of t1.i = 998address of t1.i = 998address of t1.s = 1000address of t1.s = 1000

2 bytes

5 bytes

1 byte (hole)

1 byte

1 byte (hole)

992

9981000

2 bytes

5 bytes

1 byte (hole)

1 byte

1 byte (hole)

10021001

997

t2

t1

Page 10: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Using Structures With FunctionsUsing Structures With Functions

Passing structures to functionsPassing structures to functionsPass entire structure or pass individual membersPass entire structure or pass individual members

Both pass call by valueBoth pass call by value

It is not a good idea to pass a structure to or return from function.It is not a good idea to pass a structure to or return from function.The better way is passing a pointer to the structure to the functions The better way is passing a pointer to the structure to the functions and returning a pointer from function.and returning a pointer from function.

To pass structures call-by-reference To pass structures call-by-reference Pass its addressPass its address

Pass reference to itPass reference to it

To pass arrays call-by-valueTo pass arrays call-by-valueCreate a structure with the array as a member Create a structure with the array as a member

Pass the structurePass the structure

Page 11: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Using Structures With Functions Using Structures With Functions (cont.)(cont.)

ExampleExample::day_of_year(struct date *pd)day_of_year(struct date *pd){{ int i, day, leap;int i, day, leap;

day = pd -> day;day = pd -> day; leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0;leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0; for (i=1; i<pd -> month; i++)for (i=1; i<pd -> month; i++)

day += day_tab[leap][i];day += day_tab[leap][i]; return (day);return (day);}}

The declaration The declaration struct date *pd;struct date *pd;says that says that pdpd is a is a pointerpointer to a structure of the type to a structure of the type datedateIf If pp is a pointer to a structure, then is a pointer to a structure, then p-> member_of_structurep-> member_of_structure refers to the refers to the particular members, like particular members, like pd -> yearpd -> year p-> member_of_structure p-> member_of_structure is equivalent to is equivalent to (*p).member_of_structure(*p).member_of_structureNotice:Notice: ‘.’‘.’ has higher precedence thanhas higher precedence than ‘*’‘*’;; *pd.year *pd.year is wrong, sinceis wrong, since pd.year pd.year is not a pointer.is not a pointer.BothBoth ->-> and and . . associate from associate from left to rightleft to right. So . So p -> q -> memberp -> q -> memberare are (p->q)->member. (p->q)->member. ExampleExample:: emp.birthday.month emp.birthday.month are are (emp.birthday).month(emp.birthday).month

Page 12: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Using Structures With Functions Using Structures With Functions (cont.)(cont.)

-> -> and and .. both are at the highest precedence (together with both are at the highest precedence (together with ()() for for function and function and [][] for array subscripts) for array subscripts)

ExampleExample::struct {struct {

int *x;int *x; int *y;int *y;} *p;} *p;

++p->x; ++p->x; is equivalent tois equivalent to ++(p->x) /* ++(p->x) /* increment increment x, x, not not p */p */

(++p)->x; (++p)->x; /* increment p before access x *//* increment p before access x */

*p->y; *p->y; /* fetch whatever y points to *//* fetch whatever y points to */

*p->y++; *p->y++; /* increments y after accessing whatever y point to *//* increments y after accessing whatever y point to */

(*p->y)++; (*p->y)++; /* increments whatever y point to, just like *p->y++ *//* increments whatever y point to, just like *p->y++ */

*p++->y; *p++->y; /* increments p after accessing whatever y point to */ /* increments p after accessing whatever y point to */

Page 13: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

typedeftypedef

typedeftypedef Creates synonyms (aliases) for previously defined data typesCreates synonyms (aliases) for previously defined data typesUse Use typedeftypedef to create shorter type names to create shorter type namesExample:Example:

typedef struct card *CardPtr;typedef struct card *CardPtr;Defines a new type name Defines a new type name CardPtrCardPtr as a synonym for type as a synonym for type struct card *struct card *

typedeftypedef does not create a new data type while it o does not create a new data type while it only creates an aliasnly creates an alias

ExampleExample:: struct card { const char *face; const char *suit;};

typedef struct card Card;void fillDeck( Card * const, const char *[], const char *[] );

int main(){ Card deck[ 52 ]; const char *face[] = {"Ace", "Deuce", "Three", "Four", "Five", "Six",

Seven", "Eight", “Nine", "Ten", "Jack", "Queen", "King"}; const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"}; .. .. fillDeck( deck, face, suit ); .. ..}

void fillDeck(Card * const wDeck, const char * wFace[], const char * wSuit[]){.. ..}

Page 14: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

UnionsUnionsunionunion

Memory that contains a variety of objects over timeMemory that contains a variety of objects over timeOnly contains one data member at a timeOnly contains one data member at a timeMembers of a Members of a unionunion share space share spaceConserves storageConserves storageOnly the last data member defined can be accessedOnly the last data member defined can be accessed

unionunion declarations declarationsSame as structSame as struct

union Number {union Number { int x;int x; float y;float y;};};union Number value;union Number value;

Valid Valid unionunion operations operationsAssignment to Assignment to unionunion of same type: of same type: ==Taking address: Taking address: &&Accessing union members: Accessing union members: ..Accessing members using pointers: Accessing members using pointers: ->->

Page 15: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

1 /* Fig. 10.5: fig10_05.c

2 An example of a union */

3 #include <stdio.h>

4

5 union number {

6 int x;

7 double y;

8 };

9

10 int main()

11 {

12 union number value;

13

14 value.x = 100;

15 printf( "%s\n%s\n%s%d\n%s%f\n\n",

16 "Put a value in the integer member",

17 "and print both members.",

18 "int: ", value.x,

19 "double:\n", value.y );

20

21 value.y = 100.0;

22 printf( "%s\n%s\n%s%d\n%s%f\n",

23 "Put a value in the floating member",

24 "and print both members.",

25 "int: ", value.x,

26 "double:\n", value.y );

27 return 0;

28 }

Put a value in the integer memberand print both members.int: 100double:-92559592117433136000000000000000000000000000000000000000000000.00000 Put a value in the floating memberand print both members.int: 0double:100.000000

Define union

Initialize variables

Set variables

Print

Program Output

Page 16: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Array of StructuresArray of StructuresExampleExample: (before): (before)

char name[PERSON][NAMESIZE];char name[PERSON][NAMESIZE];int tscore[PERSON]int tscore[PERSON]int math[PERSON]int math[PERSON]int english[PERSON]int english[PERSON]

Initialization of structure arrayInitialization of structure arraystruct person_data{struct person_data{

.. .. .. .... .. .. ..} person[]=} person[]={{

{“Jane”,180,89,91},{“Jane”,180,89,91},

{“John”,190,90,100},{“John”,190,90,100}, .. .. .. .... .. .. .. }; }; /* /* similar to 2D similar to 2D

arrayarray */ */

ExampleExample: using separated arrays: using separated arrays

average (int tscore, int math, int average (int tscore, int math, int eng, int n)eng, int n){{int i, total=0,mathtotal = 0, int i, total=0,mathtotal = 0, engtotal=0;engtotal=0;for (i=0; i<n, i++) {for (i=0; i<n, i++) {

total += *tscore++;total += *tscore++;mathtotal += *math++;mathtotal += *math++;engtotal += *eng++;engtotal += *eng++;

}}

struct person_data{char name[NAMESIZE];int tscore;int math;int english;

} person[PERSON];

(now)

Example: using pointer to structure

average (struct person_data *person, int n){int i, total=0,mathtotal = 0, engtotal=0;

for (i=0; i<n, i++) {total += person->tscore;mathtotal += person->math;engtotal += person->eng;person++;

}

the inner brace is not necessary

“Jane”,180,89,91,“John”,190,90,100,.. .. .. ..

Page 17: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Self-Reference StructureSelf-Reference Structure

Dynamic Data StructureDynamic Data Structure

Data Structure: link list, tree, graph, …Data Structure: link list, tree, graph, …ExampleExample: Binary Tree: Binary Tree

Struct treeNode {Struct treeNode {char word[SIZE];char word[SIZE];int count;int count;struct treeNode *left;struct treeNode *left;struct treeNode *right;struct treeNode *right;/* or /* or struct treeNode *left, *right;struct treeNode *left, *right; */ */};};

/* Inorder traversal *//* Inorder traversal */tree_print(struct treeNode *p) tree_print(struct treeNode *p)

{{if (p!=NULL){if (p!=NULL){

tree_print(p->left);tree_print(p->left);printf(“.. ..”, p->word, .. ..);printf(“.. ..”, p->word, .. ..);tree_print(p-> right);tree_print(p-> right);}}

}}

Page 18: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Link listLink list

ExampleExample: : Struct listNode {Struct listNode {

char word[SIZE];char word[SIZE];int count;int count;struct listNode *next;struct listNode *next; };};

/* Inorder traversal *//* Inorder traversal */list_print(struct listNode *p) list_print(struct listNode *p)

{{while (p!=NULL)while (p!=NULL)

{{ printf(“.. ..”, p->word, .. ..);printf(“.. ..”, p->word, .. ..); p = p->next; p = p->next;

}} }}

Page 19: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Bit FieldsBit Fields

Bit field Bit field Member of a structure whose size (in bits) has been specifiedMember of a structure whose size (in bits) has been specified

Enable better memory utilization Enable better memory utilization

Must be declared as Must be declared as intint or or unsignedunsigned

Cannot access individual bitsCannot access individual bits

Declaring bit fields Declaring bit fields Follow Follow unsignedunsigned or or intint member with a colon ( member with a colon (::) and an integer constant representing ) and an integer constant representing the width of the fieldthe width of the field

ExampleExample::

struct BitCard {struct BitCard { unsigned face : 4;unsigned face : 4; unsigned suit : 2;unsigned suit : 2; unsigned color : 1;unsigned color : 1;};};

Unnamed bit fieldUnnamed bit fieldField used as padding in the structureField used as padding in the structure

Nothing may be stored in the bitsNothing may be stored in the bits

Unnamed bit field with zero width aligns next bit field to a new storage unit boundaryUnnamed bit field with zero width aligns next bit field to a new storage unit boundary

struct Example { unsigned a : 13; unsigned : 3; unsigned b : 4;}

Page 20: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Enumeration ConstantsEnumeration Constants

EnumerationEnumerationSet of integer constants represented by identifiersSet of integer constants represented by identifiers

Enumeration constants are like symbolic constants whose values are Enumeration constants are like symbolic constants whose values are automatically setautomatically set

Values start at Values start at 00 and are incremented by and are incremented by 11

Values can be set explicitly with Values can be set explicitly with ==

Need unique constant namesNeed unique constant namesExampleExample::

enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, JUL, AUG, SEP, OCT, NOV, DEC}; AUG, SEP, OCT, NOV, DEC};

Creates a new type enum Months in which the identifiers are set to the Creates a new type enum Months in which the identifiers are set to the integers 1 to 12integers 1 to 12

Enumeration variables can only assume their enumeration constant Enumeration variables can only assume their enumeration constant values (not the integer representations)values (not the integer representations)

Page 21: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

1 /* Fig. 10.18: fig10_18.c

2 Using an enumeration type */

3 #include <stdio.h>

4

5 enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,

6 JUL, AUG, SEP, OCT, NOV, DEC };

7

8 int main()

9 {

10 enum months month;

11 const char *monthName[] = { "", "January", "February",

12 "March", "April", "May",

13 "June", "July", "August",

14 "September", "October",

15 "November", "December" };

16

17 for ( month = JAN; month <= DEC; month++ )

18 printf( "%2d%11s\n", month, monthName[ month ] );

19

20 return 0;

21 }

1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September10 October11 November12 December

Page 22: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Storage ManagementStorage Management

C supports 4 functions, C supports 4 functions, malloc(), malloc(), calloc(),free(), and cfree()calloc(),free(), and cfree() for storage for storage managementmanagement malloc(n):malloc(n):

allocate a node while its content is still ‘garbage’allocate a node while its content is still ‘garbage’

nn is an integer, indicating the size of memory in byte which you would like is an integer, indicating the size of memory in byte which you would like to allocateto allocate

malloc()malloc() return a character pointer to that memory return a character pointer to that memory

So, you have to use cast operator So, you have to use cast operator (type)(type), to change the type of the , to change the type of the pointer.pointer.

ExampleExample: :

int *ip;int *ip;

ip = (int*) malloc(sizeof(int));ip = (int*) malloc(sizeof(int));

struct treeNode *tp;struct treeNode *tp;

tp = (struct tnode *) malloc(sizeof(struct tp = (struct tnode *) malloc(sizeof(struct tnode));tnode));

Page 23: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Storage Management Storage Management (cont.)(cont.)

free(p):free(p): free()free() will release the memory allocated by will release the memory allocated by malloc(). malloc(). p p is the pointer containing the address returning fromis the pointer containing the address returning from malloc(). malloc().

ExampleExample:: int *ip;int *ip; ip = (int*) malloc(sizeof(int));ip = (int*) malloc(sizeof(int)); ... .. ..... .. ..

free(ip);free(ip); /* /* Question: can youQuestion: can you free(ip) free(ip) after after ip++ ip++ ? */? */

ExampleExample:: struct treeNode *tp;struct treeNode *tp; tp=(struct treeNode *)malloc(sizeof(struct tp=(struct treeNode *)malloc(sizeof(struct

treeNode ));treeNode )); ... .. ..... .. ..

free(tp);free(tp);

When there is no further memory, When there is no further memory, malloc()malloc() will return will return NULL NULL pointer. It is a good pointer. It is a good idea to check the returning value of idea to check the returning value of malloc().malloc().if ((ip=(int *)malloc(sizeof(int))) == NULL){if ((ip=(int *)malloc(sizeof(int))) == NULL){

printf(“\nMemory is FULL\n”);printf(“\nMemory is FULL\n”);exit(1);exit(1);

}}

When you free the memory, you must be sure that you pass the original address When you free the memory, you must be sure that you pass the original address returning fromreturning from malloc() malloc() to function to function free(). free(). Otherwise, system exception Otherwise, system exception may be happenedmay be happened

Page 24: Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui

Dale Roberts

Storage Management Storage Management (cont.)(cont.)

calloc(n,size):calloc(n,size): calloc()calloc() allow you to allocate an allow you to allocate an nn elements array of same data type. elements array of same data type. Because Because nn can be an integer variable, you can use can be an integer variable, you can use calloc()calloc() to allocate a to allocate a dynamic size array.dynamic size array.

n n is the element number of array that you want to allocate.is the element number of array that you want to allocate.

sizesize is the number of byte of each element. is the number of byte of each element.

Unlike Unlike malloc()malloc(), , calloc()calloc() guarantees that memory contents are all zero guarantees that memory contents are all zeroExampleExample: allocate an array of 10 elements: allocate an array of 10 elements

int *ip;int *ip;

ip = (int*) calloc(10, sizeof(int));ip = (int*) calloc(10, sizeof(int));

*(ip+1) *(ip+1) refer to the 2refer to the 2ndnd element, the same as element, the same as ip[1] ip[1]

*(ip+i) *(ip+i) refer to the i+1refer to the i+1thth element, the same as element, the same as ip[i] ip[i]

Like Like malloc(), calloc() malloc(), calloc() will returnwill return NULL NULL, if no further memory is available., if no further memory is available.

cfree(p):cfree(p): cfree() cfree() releases the memory allocated byreleases the memory allocated by calloc() calloc()..

ExampleExample::cfree(ip);cfree(ip);