Professional Documents
Culture Documents
Allocation
CSC-103 Programming Fundamentals
CSC-141 Introduction to Computer Programming
Lecture 20
Slides prepared by: Dr. Omar Ahmad
Lecture outline
• Memory allocation of variables and arrays in C
• Why do we need to change memory allocation at run time?
• Syntax and usage of memory allocation functions in C.
• malloc()
• calloc()
• free()
• realloc()
• Using DMA with structures
• Introduction to a dynamic array: The linked list
2
Structure Arrays
• Like other primitive types, array of struct employee
structures are also allowed in C.
{ int id;
• Here emp_list[5] is an array of
structures with 5 elements. char name[20];
float salary;
• Individual members of one of the
elements may be accessed using the };
dot operator. struct employee emp_list[5];
3
Memory Map of Structure Arrays
4
Accessing Elements in Structure Arrays
• Individual structure elements in an array follow the pattern
array_name[index].member_name
• Here emp_list[5] is an array of structures with 5 elements.
• Individual members of one of the elements may be accessed using the dot operator.
7
Structure Padding in C
• In this case, when we calculate the size of the struct student, it
struct student
comes to be 6 bytes.
• But this answer is wrong. {
• 8 bytes are allocated when a variable of this type is declared. char a; // 1 byte
• This is due to a speed-up memory access feature of C.
• See the below link for details.
char b; // 1 byte
int c; // 4 bytes
};
https://www.javatpoint.com/structure-padding-in-c
8