0% found this document useful (0 votes)
26 views38 pages

Structures

Uploaded by

Shehnil Reefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views38 pages

Structures

Uploaded by

Shehnil Reefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

CSE 225

Structures
Structures and Unions

• Essential for building up “interesting” data


structures — e.g.,
• Data structures of multiple values of different kinds
• Data structures of indeterminate size
• Essential for solving “interesting” problems
• Most of the “real” problems in the C world
Definition — Structure

• A collection of one or more variables,


typically of different types, grouped
together under a single name for convenient
handling

• Known as struct in C and C++


struct

• Defines a new type


• A new kind of data type that compiler regards as a
unit.
struct motor {
float volts; //voltage of the motor
float amps; //amperage of the motor
int phases; //# of phases of the motor
float rpm; //rotational speed of motor
}; //struct motor
struct

• Defines a new type t ype


f t he
o
e type that compiler regards as a
• A new kind of adata
N m
unit.
ta g Note:– name of type is optional
if you are just declaring a single
struct motor { struct
float volts; //voltage of the motor
float amps; //amperage of the motor
int phases; //# of phases of the motor
float rpm; //rotational speed of motor
}; //struct motor
struct

• Defines a new type


• A new kind of data type that compiler regards as a
unit.
struct motor {
float volts; //voltage of the motor
float amps; Members of the
//amperage of the motor
struct
int phases; //# of phases of the motor
float rpm; //rotational speed of motor
}; //struct motor
Declaring struct variables

struct motor p, q, r;
• Declares and sets aside storage for three variables –
p, q, and r – each of type struct motor
struct motor M[25];
• Declares a 25-element array of struct motor;
allocates 25 units of storage, each one big enough to
hold the data of one motor
struct motor *m;
• Declares a pointer to an object of type struct
motor
Structures
struct ADate {
int month;
int day;
int year;
};

struct ADate date;

date.month = 9;
date.day = 1;
date.year = 2005;

To display the screen locations stored in the structure Adate,


printf("%d, %d, %d", date.month, date.day,
date.year);
What are the Advantage ??
struct ADate {
int month;
int day;
int year;
};

struct ADate date1, date2;

date1.month = 9;
date1.day = 1;
date1.year = 2005;

date2 = date1 ;

date2.month = date1.month;
date2.day = date1.day;
date2.year = date1.year;
More Examples
• struct SSN { • struct time {
int first_three; int hours;
char dash1; int minutes;
int second_two; int seconds;
char dash2; } time_of_birth = { 8, 45, 0 };
int last_four;
};
struct SSN customer_ssn ;

• struct date {
char month[2];
char day[2];
char year[4];
} current_date ;
Structure Representation & Size
•sizeof(struct …) =
• sum of sizeof(field) struct CharCharInt {
•+ alignment padding char c1;
Processor- and compiler-specific char c2;
int i;
} foo;

foo.c1 = ’a’;
foo.c2 = ’b’;
foo.i = 0xDEADBEEF;

c1 c2 padding i

61 62 EF BE AD DE
x86 uses “little-endian” representation
Accessing Members of a struct
Repeat
struct motor {
float volts;
• Let
float amps;
struct motor p; int phases; otor
struct motor q[10]; float rpm;
• Then };
p.volts — is the voltage
p.amps — is the amperage
p.phases — is the number of phases
p.rpm — is the rotational speed

q[i].volts — is the voltage of the ith motor


q[i].rpm — is the speed of the ith motor
Accessing Members of a struct (continued)

• Let
s e s ?
struct motor *p;nthe
pa re
• Then Why the
(*p).volts — is the voltage of the motor pointed
to by p
(*p).phases — is the number of phases of the

motor pointed to by p
Accessing Members of a struct (continued)

• Let e r a t or
o p ce
struct motor ' . '
*p;eced e n
a us e r
Be c e r p
• g
Then has h ary '*'
i h
n u n
tha — is the voltage of the motor pointed
(*p).volts
to by p
(*p).phases — is the number of phases of the

motor pointed to by p
Accessing Members of a struct (continued)

• Let
struct motor *p;
• Then
(*p).volts — is the voltage
Reason:– of the
you really motor
want pointed
the expression
to by p
m.volt * m.amps
(*p).phases — is the number of phases of the
to mean what you think it should mean!
motor pointed to by p
Accessing Members of a struct (continued)

• The (*p).member notation is a nuisance


• Clumsy to type; need to match ( )
• Too many keystrokes

• This construct is so widely used that a


special notation was invented, i.e.,
– p->member, where p is a pointer to the
structure
Previous Example Becomes …

• Let
struct motor *p;
• Then
p -> volts — is the voltage of the motor pointed
to by p
p -> phases — is the number of phases of the

motor pointed to by p
Operations on struct
• Copy/assign
struct motor p, q;
p = q;
• Get address
struct motor p;
struct motor *s
s = &p;
• Access members
p.volts;
s -> amps;
Initialization of a struct
• Let struct motor {
float volts;
float amps;
int phases;
float rpm;
}; //struct motor
• Then
struct motor m = {208, 20, 3,
1800};
initializes the struct
Why structs AGAIN???

• Open-ended data structures


– E.g., structures that may grow during
processing
– Avoids the need for realloc() and a lot of
copying

• Self-referential data structures


– Lists, trees, etc.
Nesting Structures
struct Point pt;
struct Point { pt
char name[30]; Name x y
int x;
int y;
};

struct Line {
struct Point pt1;
struct Point pt2;
};
struct Line l1;
Nesting Structures

struct Point {
l1
char name[30];
pt1 pt2
int x;
int y;
};

x y Name x y
struct Line { Name

10
struct Point pt1;
struct Point pt2;
}; To Access the Elements
struct Line l1;
l1.pt1.x=10;
struct Point {
char name[30];
Array of Structures int x;
int y;
};
• Array of Structures act like any other array.
struct Point pt[3];

pt[0].name = “A”; pt[1].name = “B”; pt[2].name = “mid”;


pt[0].x = 0; pt[1].x = 4; pt[2].x = (pt[0].x + pt[1].x)/2;
pt[0].y = 1; pt[1].y = 1; pt[2].y = (pt[0].y + pt[1].y)/2;

• Memory occupied: the dimensions of the


array multiply by sizeof(struct tag)
– (Remember) sizeof() is compile time function
Pointers in Structures
• A structure can have a pointer as its member

struct Point { struct Point pt;


char *namePtr;
pt
int x;
int y; namePtr x y
};

pt.namePtr=(char *) malloc(20*sizeof(char));
*(pt.namePtr)=“lastPoint”;
pt
namePtr x y

lastPoint \0
Pointer to Structures

• A pointer to a structure can be defined

struct Point p1, *ptr;


ptr=&p1;

p1.x=10 ≡ ptrx =10 ≡ (*ptr).x=10 ≡ (&p1)x = 10


Self referencing Structures

• Useful in data structures like trees, linked lists.


• It is illegal for a structure to contain an instance of itself.
– Solution: Have a pointer to another instance.
struct lnode { /* the linked list node */
int value;
struct lnode *nextPtr; /* pointer to next node */
} n1,n2;
n1 n2
value nextPtr value nextPtr
0 NULL 0 NULL
Example
e ga l!
struct item { is l
is
! T h
char *s; Yes
struct item *next;
}
• I.e., an item can point to another item
• … which can point to another item
• … which can point to yet another item
• … etc.
Thereby forming a list of items
Self referencing Structures
struct lnode { n1.value=10;
int value; n1.nextPtr=&n2;
struct lnode *nextPtr; n2.value=20;
} n1,n2;
n2.nextPtr=NULL;
basePtr struct lnode *basePtr=&n1;
0x1000

n1 n2
value nextPtr value nextPtr
10 0x2000 20 NULL

0x1000 0x2000
Typedef
• Use typedef for creating new data type names
• typedef int length;
this the name length a synonym (alias) for int. Afterwards, you can
do: length x = 4;
• In context of structs, you can do:

struct Point { typedef struct Point *pointPtr; typedef struct lnode {


int x; pointPtr p1; .
int y; struct Point p2; .
}; p2.x=20; } myNode;
typedef struct Point myPoint; p1.x=10; ?? myNode n1, *ptr;
myPoint p1; p1x=10; ??
struct Point p2; p1=&p2; typedef struct {
p1.x=10; p1x=10; ?? .
p1=(pointPtr) malloc(sizeof(struct Point)); .
p1x=10; ?? } myNode;
myNode n1, *ptr;
typedef (continued)

• typedef may be used to rename any type


– Convenience in naming
– Clarifies purpose of the type
– Cleaner, more readable code
– Portability across platforms o m
e
C f
+ r +
• E.g., a n
dg
y Cc han
– typedef char *String; e
o m
n ian orm
t h e
rm l a tfode!
• E.g., e
y sceo m t o p
l e c f i l e!
VTehr latforpmortab in a .h
– typedef int size_t; p . for nce
– typedef long int32; Esp fined o
– typedef long long int64; De
Unions
• A union is a memory location that is shared by two or more
different types of variables.
union u_tag {
int ival;
float fval;
char cval;
} u;

• Each of ival, fval, cval have the same location in memory.


• sizeof(union …) = maximum of sizeof(field)
• Usage is similar to that of structs: u.ival or u.cval
• Up to programmer to determine how to interpret a union (i.e.
which member to access) and used for low-level programming
Example

union AnElt {
int i;
char c;
} elt1, elt2;

elt1.i = 4;
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;

c padding

EF BE AD DE
i
Unions

• Storage
– size of union is the size of its largest member
– avoid unions with widely varying member
sizes;
for the larger data types, consider using
pointers instead
• Initialization
– Union may only be initialized to a value
appropriate for the type of its first member
Bit-fields

• When storage is high cost affair, we need to use


memory efficiently (e.g in embedded systems)
struct {
unsigned pin1 : 1;
unsigned pin2 : 2;
unsigned pin3 : 1;
} flags;

• Here each of the element takes a bit of memory


(1 bit)
• The number following the colons represent the
field length in bits.
Looking Ahead

• The rest of this course is about data


structures that you will typically encounter
in C programs in your professional lives

• All of them involve structs.


Another note about structs

• The following is not legal:–


struct motor {
float volts;
float amps;
float rpm;
unsigned int phases;
}; //struct motor

You must write


motor m; struct motor m;
motor *p; struct motor *p;
Revisit note about structs and pointers

• The following is legal:–


/* in a .c or .h file */
typedef struct _item Item;
Item *p, *q;

… /* In another file */
struct _item {
char *info;
Item *nextItem;
};
Questions?

You might also like