t15BStructuresFunctionsAndArrays Pps
t15BStructuresFunctionsAndArrays Pps
CSCI 230
Structures
Functions and Arrays
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: [email protected]
Dale Roberts
Using Structures With Functions
Passing structures to functions
Pass entire structure or pass individual members
Both pass call by value
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
and returning a pointer from function.
To pass structures call-by-reference
Pass its address
Pass reference to it
To pass arrays call-by-value
Create a structure with the array as a member
Pass the structure
Dale Roberts
Using Structures With Functions (cont.)
Example:
day_of_year(struct date *pd)
{
int i, day, leap;
Dale Roberts
Using Structures With Functions (cont.)
-> and . both are at the highest precedence (together with () for
function and [] for array subscripts)
Example:
struct {
int *x;
int *y;
} *p;
Dale Roberts
typedef
typedef
Creates synonyms (aliases) for previously defined data types
Use typedef to create shorter type names
Example:
typedef struct card *CardPtr;
Defines a new type name CardPtr as a synonym for type struct card *
typedef does not create a new data type while it only creates an alias
Example: 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[])
{
.. ..
}
Dale Roberts
Array of Structures
Example: (before) struct person_data{
char name[PERSON][NAMESIZE]; char name[NAMESIZE];
int tscore[PERSON] int tscore;
int math[PERSON] (now) int math;
int english[PERSON] int english;
} person[PERSON];
Initialization of structure array
struct person_data{
.. .. .. .. the inner brace is not necessary
} person[]={
{Jane,180,89,91},
{John,190,90,100},
Jane,180,89,91,
John,190,90,100,
.. .. .. .. .. .. .. ..
}; /* similar to 2D array */
Dale Roberts
1 /* Fig. 10.5: fig10_05.c
2 An example of a union */
3 #include <stdio.h>
4
5 union number {
Define union
6 int x;
7 double y;
8 };
9
10 int main()
11 {
12 union number value; Initialize variables
13
Set variables
14 value.x = 100;
15 printf( "%s\n%s\n%s%d\n%s%f\n\n", Print
16 "Put a value in the integer member",
17 "and print both members.",
18 "int: ", value.x,
Program Output
19 "double:\n", value.y ); Put a value in the integer member
20 and print both members.
int: 100
21 value.y = 100.0;
double:
22 printf( "%s\n%s\n%s%d\n%s%f\n", -
23 "Put a value in the floating member", 9255959211743313600000000000000000000000000
24 "and print both members.", 0000000000000000000.00000
25 "int: ", value.x,
Put a value in the floating member
26 "double:\n", value.y );
and print both members.
27 return 0; int: 0
28 } double:
100.000000
Dale Roberts
Bit Fields
Bit field
Member of a structure whose size (in bits) has been specified
Enable better memory utilization
Must be declared as int or unsigned
Cannot access individual bits
struct BitCard {
unsigned face : 4;
unsigned suit : 2;
unsigned color : 1;
}; struct Example {
unsigned a : 13;
Unnamed bit field unsigned : 3;
Field used as padding in the structure unsigned b : 4;
}
Nothing may be stored in the bits
Unnamed bit field with zero width aligns next bit field to a new storage unit boundary
Dale Roberts
Enumeration Constants
Enumeration
Set of integer constants represented by identifiers
Enumeration constants are like symbolic constants whose values are
automatically set
Values start at 0 and are incremented by 1
Values can be set explicitly with =
Need unique constant names
Example:
enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL,
AUG, SEP, OCT, NOV, DEC};
Creates a new type enum Months in which the identifiers are set to the
integers 1 to 12
Enumeration variables can only assume their enumeration constant
values (not the integer representations)
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", 1 January
13 "June", "July", "August", 2 February
3 March
14 "September", "October", 4 April
15 "November", "December" }; 5 May
16 6 June
7 July
17 for ( month = JAN; month <= DEC; month++ ) 8 August
18 printf( "%2d%11s\n", month, monthName[ month ] ); 9 September
19 10 October
11 November
20 return 0; 12 December
21 }
Dale Roberts
Storage Management
C supports 4 functions, malloc(), calloc(),free(),
and cfree() for storage management
malloc(n):
allocate a node while its content is still garbage
n is an integer, indicating the size of memory in byte which you would like
to allocate
malloc() return a character pointer to that memory
So, you have to use cast operator (type), to change the type of the
pointer.
Example:
int *ip;
ip = (int*) malloc(sizeof(int));
struct treeNode *tp;
tp = (struct tnode *) malloc(sizeof(struct tnode));
Dale Roberts
Storage Management (cont.)
free(p):
free() will release the memory allocated by malloc().
p is the pointer containing the address returning from malloc().
Example:
int *ip;
ip = (int*) malloc(sizeof(int));
... .. ..
free(ip); /* Question: can you free(ip) after ip++ ? */
Example:
struct treeNode *tp;
tp=(struct treeNode *)malloc(sizeof(struct treeNode ));
... .. ..
free(tp);
When there is no further memory, malloc() will return NULL pointer. It is a
good idea to check the returning value of malloc().
if ((ip=(int *)malloc(sizeof(int))) == NULL){
printf(\nMemory is FULL\n);
exit(1);
}
When you free the memory, you must be sure that you pass the original
address returning from malloc() to function free(). Otherwise, system
exception may be happened
Dale Roberts
Storage Management (cont.)
calloc(n,size):
calloc() allow you to allocate an n elements array of same data type.
Because n can be an integer variable, you can use calloc() to allocate a
dynamic size array.
n is the element number of array that you want to allocate.
size is the number of byte of each element.
Unlike malloc(), calloc() guarantees that memory contents are all zero
Example: allocate an array of 10 elements
int *ip;
ip = (int*) calloc(10, sizeof(int));