You are on page 1of 28

Structures and Unions in C

Alan L. Cox
alc@rice.edu
Structures can be created and accessed using
pointers. A pointer variable of a structure can
be created as below: struct name
{ member1; member2; . . }; int main()
{ struct name *ptr; } Here, the pointer
variable of type struct name is created.

Cox Structures and Unions 2


Objectives

Be able to use compound data structures in


programs

Be able to pass compound data structures as


function arguments, either by value or by
reference

Be able to do simple bit-vector manipulations

Cox Structures and Unions 3


Structures
Compound data: struct ADate {
int month;
int day;
A date is
int year;
 an int month and
};
 an int day and
 an int year struct ADate date;

date.month = 2;
date.day = 4;
date.year = 2021;

Unlike Java, C doesn’t


automatically define functions for
initializing and printing …

Cox Structures and Unions 4


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

Cox Structures and Unions 5


Typedef

Mechanism for creating new type names


 New names are an alias for some other type
 May improve the portability and/or clarity of the
program
Overload existing type
typedef long int64_t; names for portability
typedef struct ADate {
int month;
int day;
int year;
} Date; Simplify complex type names

int64_t i = 100000000000;
Date d = { 2, 4, 2021 };

Cox Structures and Unions 6


Constants

Allow consistent use of the same constant


throughout the program
 Improves clarity of the program
 Reduces likelihood of simple errors
 Easier to update constants in the program
Constant names are
Preprocessor directive capitalized by convention

#define SIZE 10
Define once,
int array[10]; int array[SIZE]; use throughout
the program

for (i=0; i<10; i++) { for (i=0; i<SIZE; i++) {


… …
} }
Cox Structures and Unions 7
Arrays of Structures
Array declaration Constant

Date birthdays[NFRIENDS];

bool
check_birthday(Date today)
{
int i; Array index, then
structure field
for (i = 0; i < NFRIENDS; i++) {
if ((today.month == birthdays[i].month) &&
(today.day == birthdays[i].day))
return (true);

return (false);
}

Cox Structures and Unions 8


Bit-field Structures
Special syntax packs
structure values more struct Flags {
tightly int f1:3;
unsigned int f2:1;
unsigned int f3:2;
Similar to bit vectors, but
} my_flags;
arguably easier to read
 Nonetheless, bit vectors my_flags.f1 = -2;
are more commonly my_flags.f2 = 1;
used.
my_flags.f3 = 2;

Padded to be an integral
number of words f1 f2 f3

 Placement is compiler- 1 1 0 1 1 0 … …
specific.

Cox Structures and Unions 9


Unions
Choices:
union AnElt {
int i;
An element is
char c;
 an int i or
} elt1, elt2;
 a char c
elt1.i = 4;
sizeof(union …) = elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
maximum of sizeof(field)

c padding

EF BE AD DE
i

Cox Structures and Unions 10


Unions
A union value doesn’t “know” which case it contains

?
union AnElt {
int i;
char c;
How should your program keep track
} elt1, elt2;
whether elt1, elt2 hold an int or
elt1.i = 4;
a char?
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
?
Basic answer: Another variable holds
if (elt1 currently has a char) … that info

Cox Structures and Unions 11


Tagged Unions

Tag every value with its case

I.e., pair the type info together with the union


Implicit in Java, Scheme, ML, …

enum Union_Tag { IS_INT, IS_CHAR };


struct TaggedUnion { Enum must be external to struct,
enum Union_Tag tag; so constants are globally visible.
union {
int i;
char c;
} data;
Struct field must be named.
};

Cox Structures and Unions 12


Pointers to Structures
Structures can be created and accessed using pointers.
A pointer variable of a structure can be created as
below:
struct name {
member1;
member2;
..
};
int main()
{
struct name *ptr;
}
Here, the pointer variable of type struct name is
created.

Structures and Unions 13


Pointers to Structures

Date void
create_date1(int month, create_date2(Date *d,
int day, int month,
int year) Pass-by-reference int day,
{ int year)
Date d; {
d->month = month;
d.month = month; d->day = day;
d.day = day; d->year = year;
d.year = year; }

return (d);
Date today;
}

today = create_date1(2, 4, 2021);


Copies date create_date2(&today, 2, 4, 2021);

Structures and Unions 14


Pointers to Structures (cont.)
void
create_date2(Date *d,
int month,
0x30A8 year: 2021
int day, 0x30A4 day: 4
int year)
{
0x30A0 month: 2
d->month = month; 0x3098 d: 0x1000
d->day = day;
d->year = year;
}

void 0x1008 today.year: 2021


fun_with_dates(void)
{ 0x1004 today.day: 4
Date today; 0x1000 today.month: 2
create_date2(&today, 2, 4, 2021);
}

Structures and Unions 15


SELF REFERENCIAL STRUCTURES
Self referential structures contain a pointer member
that points to a structure of the same structure type.
In other words, a self-referential C structure is the one
which includes a pointer to an instance of itself.
Syntax of Self-Referential Structure in C Programming
struct demo
{
Data_type member1, member2;
struct demo *ptr1,*ptr2;
}

Structures and Unions 16


• As you can see in the syntax, ptr1 and ptr2
are structure pointers that are pointing to the
structure demo, so structure demo is a self
referential structure.
• These types of data structures are helpful in
implementing data structures like linked lists
and trees.
• It is an error to use a structure variable as a
member of its own struct type structure or
union type union, respectively.

Structures and Unions 17


Self Referential Structure Example
struct node
{
int data;
struct node*nextPtr;
}

nextPtr : is a pointer member that points to a structure


of the same type as the one being declared. It is
referred to as a link. Links can tie one node to another
node.
The concept of linked lists,, stacks, queues, trees and
many others works on the principle of self-referential
structures.

Structures and Unions 18


Unions

• A union, is a collection of variables of different types,


just like a structure. However, with unions, you can
only store information in one field at any one time
• You can picture a union as like a block of memory
that is used to store variables of different types.
• Once a new value is assigned to a field, the existing
data is wiped over with the new data.
A union can also be viewed as a variable type that can
contain many different variables (like a structure), but
only actually holds one of them at a time (not like a
structure).
•This can save memory if you have a group of data
where only one of the types is used at a time. The size
of a union is equal to the size of it's largest data or
element
Structures and Unions 19
Union Declaration
union union-type-name
{
type variable-names;
type variable-names;
… ...
}[union variable];
The compiler will allocate enough storage in a number
to accommodate the largest element in the union.
Elements of a union are accessed in the same manner
as a struct.

Structures and Unions 20


Bit Fields

Bit field – Member of a structure whose size (in bits) has


been specified.
– Enable better memory utilization – Must be defined as
int or unsigned
– Cannot access individual bits
• Defining bit fields – Follow unsigned or int member
with a colon (:) and an integer constant representing
the width of the field
– Example:
struct BitCard
{
unsigned face : 4;
unsigned suit : 2;
unsigned color : 1;
}; 1
Structures and Unions 21
Like a struct, except
• Each member is a bit-field within a word
• Accessed like members of a struct
• Fields may be named or unnamed
• Machine-dependent
• Order of bits in word
• Size of word

Structures and Unions 22


typedef
The C programming language provides a keyword
called typedef, which you can use to give a type, a
new name.
Syntax:
typedef data_type new_name;
•typedef: It is a keyword.
• data_type: It is the name of any existing type or user
defined type created using structure/union.
• new_name: alias or new name you want to give to
any existing type or user defined type.
typedef unsigned char BYTE;
• After this type definition, the identifier BYTE can be
used as an abbreviation type unsigned char, for
example.. For the BYTE b1, b2;

Structures and Unions 23


Structures with typedef:
Struct student
{
int mark [2];
char name [10];
float average;
}
Variable for the above structure can be declared in two
ways
1st way :
• struct student record; /* for normal variable*/
struct student *record; /* for pointer variable*/
2nd way : • typedef struct studentstatus;

Structures and Unions 24


// Structure using typedef:
#include #include typedef struct student { int id; char
name[20]; float percentage; } status; int main()
{ status record; record.id=1; strcpy(record.name,
"Raju"); record.percentage = 86.5; printf(" Id is:
%d \n", record.id); printf(" Name is: %s \n",
record.name); printf(" Percentage is: %f \n",
record.percentage); return 0; }

Cox Structures and Unions 25


Enumeration data type:
An enumeration is a user-defined data type that
consists of integral constants. To define an
enumeration, keyword enum is used.
Syntax:
enum flag ,const1, const2,……constN
};
• Here, name of the enumeration is flag. Constants like
const1, const2,...., constN are values of type flag. By
default, const1 is 0, const2 is 1 and so on.
You can change default values of enum elements during
declaration (if necessary).
// Changing the default value of enum elements enum
suit
{ club=0; diamonds=10; hearts=20; spades=3; };

Structures and Unions 26


Declaration

enum boolean
{
false;
true;
};
enum boolean check;
Here, a variable check is declared which is of
type enum boolean.

Cox Structures and Unions 27


#include enum week{ sunday, monday,
tuesday, wednesday, thursday, friday,
saturday}; int main() { enum week today;
today=wednesday; printf("%d
day",today+1); return 0; } Output 4 day

Cox Structures and Unions 28

You might also like