100% found this document useful (1 vote)
32 views

C Struc

The structure contains: - An array of 5 shorts, each 2 bytes = 5 * 2 = 10 bytes - A union with the largest member being long which is 8 bytes Total size is 10 + 8 = 18 bytes The size is the sum of the largest members, ignoring padding and alignment.

Uploaded by

snehaartist2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
32 views

C Struc

The structure contains: - An array of 5 shorts, each 2 bytes = 5 * 2 = 10 bytes - A union with the largest member being long which is 8 bytes Total size is 10 + 8 = 18 bytes The size is the sum of the largest members, ignoring padding and alignment.

Uploaded by

snehaartist2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Faculty of Engineering and Technology

Department of Computing Technologies

Course: Programming in C (ADD-ON COURSE)

Week4 – Structures and Unions


Structures in C
• Structure is user-defined datatype which allows us to combine the
different datatypes together.
• Structure in the linked list is used to store data of the node as well as
the pointer to the next node's address.
• A linked list is a linear collection of similar data where the next node
is reached using the previous node in the list.
• Structure helps to create this abstract data type(ADT) in C as there
are no existing data types in C which helps in providing this ADT.
Defining Structures and Creating Objects
//Definition of structure with a member of one integer
variable and self-referential structure.
“node” is the tag
name struct node
{
“struct node” is the new n1
type
unsigned int data;
struct node *next; data next
};
n2
struct node n1;
data next
struct node n2;
structure is easy to point to the next node using
self-referential structure and also if we have the
address of the struct variable we can access any
member value.
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;
Structure Representation & Size
struct CharCharInt {
char c1;
sizeof(struct …) = char c2;
sum of sizeof(field) int i;
} foo;
+alignment padding
Processor- and compiler-specific
foo.c1 = ’a’;
foo.c2 = ’b’;
foo.i = 0xDEADBEEF;
c1 c2 padding i

61 62 EF BE AD DE
x86 uses “little-endian” representation
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 };
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++) {
… …
} }
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);
}
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);
Pointers to Structures (cont.)
void
create_date2(Date *d,
0x30A8 year: 2021
int month,
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;
create_date2(&today, 2, 4, 2021); 0x1000 today.month: 2
}
Structure in Single, and Doubly Linked List
struct node { head Declaration of Single linked list
int data;
struct node* next;
A B C
};

struct node {
int data;
Declaration of Doubly linked list
head tail
struct node* next;
struct node* prev;
}; A B C
Unions
•Choices:
union AnElt {
int i;
•An element is char c;
} elt1, elt2;
• an int i or
• a char c elt1.i = 4;
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
•sizeof(union …) =
maximum of sizeof(field)
c padding

EF BE AD DE
i
Unions
• A union value doesn’t “know” which case it contains

union AnElt {
int i;
char c;
?
} elt1, elt2;
How should your program keep track
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
Difference between structure and union
Point of
Structure Union
Difference
Allocates memory only for the largest
Memory Allocation Allocates memory for all its members.
member.
Total Size Sum of sizes of all members. Size of the largest member.
Can store values for all members Can store value for only one member at a
Data Storage
simultaneously. time.
When you want to group different data When you want to save memory and only
Use Case
types and access all of them at once. need one data type at a time.
struct example { union example {
int a; int a;
Example
float b; float b;
} }
Accessing All members can be accessed at any Only the last stored member can be
Members time. accessed.
Modification Modifying a member doesn’t affect Modifying one member may overwrite
Question 1

1. Assume that objects of the type short, float and long occupy 2 bytes,
4 bytes and 8 bytes, respectively. The memory requirement for
variable t, ignoring alignment
struct {
short s [5];
union {
float y;
long z;
}u;
} t;
a. 22 bytes
b. 18 bytes b) 18 bytes
c. 14 bytes
d. 10 bytes
Question 2

The output of the following C program is


#include< stdio.h >
a. 0, c
struct Ournode{
b. 0, a+2
char x,y,z; c. ‘0’, ‘a+2’
}; d. ‘0’,’c’
int main(){
struct Ournode p = {‘1’, ‘0’, ‘a’+2};
struct Ournode *q = &p;
a) 0,c
printf (“%c, %c”, *((char*)q+1), *((char*)q+2));
return 0;
}
Question 3

union test
{
int x; a. 12
char arr[8]; b. 16
c. 8
int y;
d. Compile error
};
int main()
{
printf("%d", sizeof(union test)); c) 8
return 0;
}
Predict the output of above program. Assume
that the size of an integer is 4 bytes and size of
character is 1 byte. Also assume that there is no
alignment needed.
4. What is the size of a structure in C?
Answer: The size of a structure in C is determined by the sum of the sizes of
its individual members, including any padding added by the compiler for
alignment.
5. What is structure padding, and why does it occur?
Answer: Structure padding is the insertion of unused bytes between
structure members to ensure proper alignment. It occurs because some data
types, like double or long, may require specific memory alignments for
efficient access.
6. How can you avoid structure padding in C?
Answer: You can use compiler-specific attributes or pragmas (e.g., #pragma
pack(1)) to control or eliminate structure padding. However, this might make
your code non-portable

You might also like