SlideShare a Scribd company logo
1 of 76
C Basics for Data Structures
Bridge Course
(27.07.2020 – 31.07.2020)
Dr. P. Subathra
Professor
Dept. of Information Technology
KAMARAJ College of Engineering and Technology
Madurai
Tamil Nadu
India
subathrakishore@yahoo.com
8/14/2020
Topics
• Arrays
• Pointers
• Structures
8/14/2020
Functions
Arrays
1. What is an Array?
2. How is it stored in the Memory?
3. Why isn’t there any boundary for an Array?
4. How is a program allocated memory in a system
during compilation and execution?
5. What is a Pointer?
6. What actually is an Array variable?
7. How is Static Memory allocation done for an
Array in C?
8. How is Dynamic Memory allocation done for an
Array in C?
8/14/2020
Arrays - Pointers
1. What is an Array?
2. How is it stored in the Memory?
3. Why isn’t there any boundary for an Array?
4. How is a program allocated memory in a system
during compilation and execution?
5. What is a Pointer?
6. What is a Pointer to a Pointer?
7. What actually is an Array variable?
8. How is Static Memory allocation done for an
Array in C?
9. How is Dynamic Memory allocation done for an
Array in C?
8/14/2020
Introduction
• Arrays
– Structures of related data items
– Static entity - same size throughout program
• A few types
– C-like, pointer-based arrays
– C++, arrays as objects
Arrays
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that all
elements of this array have
the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the element
within array c
Declaring Arrays
• Declaring arrays - specify:
– Name
– Type of array
– Number of elements
– Examples
int c[ 10 ];
float hi[ 3284 ];
• Declaring multiple arrays of same type
– Similar format as other variables
– Example
int b[ 100 ], x[ 27 ];
Examples Using Arrays
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
– If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
– Sets all the elements to 0
• If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore n is a 5 element array
9
Problem with Arrays
• Sometimes
– Amount of data cannot be predicted beforehand
– Number of data items keeps changing during program
execution
• One solution: find the maximum possible value of N and allocate
an array of N elements
– Wasteful of memory space, as N may be much smaller in some
executions
– Example: maximum value of N may be 10,000, but a particular
run may need to search only among 100 elements
• Using array of size 10,000 always wastes memory in most
cases
10
Better Solution
• Dynamic memory allocation
– Know how much memory is needed after the program is
run
• Example: ask the user to enter from keyboard
– Dynamically allocate only the amount of memory needed
• C provides functions to dynamically allocate memory
– malloc, calloc, realloc
11
Memory Allocation Functions
• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the memory.
• free
– Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
12
Allocating a Block of Memory
• A block of memory can be allocated using the
function malloc
– Reserves a block of memory of specified size and
returns a pointer of type void
– The return pointer can be type-casted to any
pointer type
• General format:
type *p;
p = (type *) malloc (byte_size);
13
Example
p = (int *) malloc(100 * sizeof(int));
– A memory space equivalent to 100 times the
size of an int bytes is reserved
– The address of the first byte of the allocated
memory is assigned to the pointer p of type int
p
400 bytes of space
14
Contd.
• cptr = (char *) malloc (20);
Allocates 20 bytes of space for the pointer cptr of type
char
• sptr = (struct stud *) malloc(10*sizeof(struct stud));
Allocates space for a structure array of 10 elements. sptr
points to a structure element of type struct stud
Always use sizeof operator to find number of bytes for a data type, as
it can vary from machine to machine
15
Points to Note
• malloc always allocates a block of contiguous bytes
– The allocation can fail if sufficient contiguous
memory space is not available
– If it fails, malloc returns NULL
if ((p = (int *) malloc(100 * sizeof(int))) == NULL)
{
printf (“n Memory cannot be allocated”);
exit();
}
16
Releasing the Allocated Space: free
• An allocated block can be returned to the system for
future use by using the free function
• General syntax:
free (ptr);
where ptr is a pointer to a memory block which has
been previously created using malloc
• Note that no size needs to be mentioned for the
allocated block, the system remembers it for each
pointer returned
Pointer Artihmetic
8/14/2020
8/14/2020
P=(int*) malloc(10);
}
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
Operations not allowed on Pointers
• Addition of two pointers
• Multiplication of Two pointers
• Multiplying a constant to a pointer
• Division of Pointers
• Division of a Pointer by a Constant
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
Pointer to 1D Array
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
Pointers in 2D Arrays
• Dynamic Allocation done at the HEAP
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
7000
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
68
Pointers to Pointers
• Pointers are also variables (storing addresses), so
they have a memory location, so they also have an
address
• Pointer to pointer – stores the address of a pointer
variable
int x = 10, *p, **q;
p = &x;
q = &p;
printf(“%d %d %d”, x, *p, *(*q));
will print 10 10 10 (since *q = p)
69
Allocating Pointer to Pointer
int **p;
p = (int **) malloc(3 * sizeof(int *));
p
p[2]
p[1]
p[0]
int ** int *
int *
int *
2D array
70
#include <stdlib.h>
int main()
{
int **array;
array = (int**) malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
{
array[i] = (int*)malloc(ncolumns * sizeof(int));
}
{
Arrays in C CS-2301, B-Term 2009 71
Arrays as Function Parameters
• void init(float A[], int arraySize);
void init(float *A, int arraySize);
• Are identical function prototypes!
• Pointer is passed by value
• I.e. caller copies the value of a pointer to
float into the parameter A
• Called function can reference through that
pointer to reach thing pointed to
Arrays in C CS-2301, B-Term 2009 72
Arrays as Function Parameters (continued)
• void init(float A[], int arraySize){
int n;
for(n = 0; n < arraySize; n++)
A[n] = (float)n;
} //init
• Assigns values to the array A in place
– So that caller can see the changes!
Allocating new heap memory
CS 3090: Safety Critical Programming in C 73
void *malloc(size_t size);
• Allocate a block of size bytes,
return a pointer to the block
(NULL if unable to allocate block)
void *calloc(size_t num_elements,
size_t element_size);
• Allocate a block of num_elements * element_size bytes,
initialize every byte to zero,
return pointer to the block
(NULL if unable to allocate block)
Note: void * denotes a generic pointer type
Allocating new heap memory
CS 3090: Safety Critical Programming in C 74
void *realloc(void *ptr, size_t new_size);
 Given a previously allocated block starting at ptr,
 change the block size to new_size,
 return pointer to resized block
 If block size is increased, contents of old block may be copied to a
completely different region
 In this case, the pointer returned will be different from the ptr argument,
and ptr will no longer point to a valid memory region
 If ptr is NULL, realloc is identical to malloc
 Note: may need to cast return value of malloc/calloc/realloc:
char *p = (char *) malloc(BUFFER_SIZE);
Deallocating heap memory
CS 3090: Safety Critical Programming in C 75
void free(void *pointer);
• Given a pointer to previously allocated memory,
– put the region back in the heap of unallocated memory
• Note: easy to forget to free memory when no longer
needed...
– especially if you’re used to a language with “garbage
collection” like Java
– This is the source of the notorious “memory leak” problem
– Difficult to trace – the program will run fine for some time,
until suddenly there is no more memory!
Any Doubts…???!!!
8/14/2020

More Related Content

What's hot

Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 

What's hot (20)

Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Tensor flow (1)
Tensor flow (1)Tensor flow (1)
Tensor flow (1)
 
Tensorflow - Intro (2017)
Tensorflow - Intro (2017)Tensorflow - Intro (2017)
Tensorflow - Intro (2017)
 
Learning stochastic neural networks with Chainer
Learning stochastic neural networks with ChainerLearning stochastic neural networks with Chainer
Learning stochastic neural networks with Chainer
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Introduction to Machine Learning with TensorFlow
Introduction to Machine Learning with TensorFlowIntroduction to Machine Learning with TensorFlow
Introduction to Machine Learning with TensorFlow
 
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
 
Chapter16 pointer
Chapter16 pointerChapter16 pointer
Chapter16 pointer
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocation
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Tensor board
Tensor boardTensor board
Tensor board
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
Introduction to Tensorflow
Introduction to TensorflowIntroduction to Tensorflow
Introduction to Tensorflow
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
NumPy/SciPy Statistics
NumPy/SciPy StatisticsNumPy/SciPy Statistics
NumPy/SciPy Statistics
 
Tensorflow windows installation
Tensorflow windows installationTensorflow windows installation
Tensorflow windows installation
 
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviScientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
 
PyTorch for Deep Learning Practitioners
PyTorch for Deep Learning PractitionersPyTorch for Deep Learning Practitioners
PyTorch for Deep Learning Practitioners
 

Similar to 1. C Basics for Data Structures Bridge Course

Ctutorial-Pointers 1.ppt
Ctutorial-Pointers 1.pptCtutorial-Pointers 1.ppt
Ctutorial-Pointers 1.ppt
DEEPAK948083
 

Similar to 1. C Basics for Data Structures Bridge Course (20)

final GROUP 4.pptx
final GROUP 4.pptxfinal GROUP 4.pptx
final GROUP 4.pptx
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
aspice
aspiceaspice
aspice
 
dynamic_v1-3.pptx
dynamic_v1-3.pptxdynamic_v1-3.pptx
dynamic_v1-3.pptx
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Data Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory AllocationData Structure - Dynamic Memory Allocation
Data Structure - Dynamic Memory Allocation
 
SimpleArray between Python and C++
SimpleArray between Python and C++SimpleArray between Python and C++
SimpleArray between Python and C++
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
 
Ctutorial-Pointers 1.ppt
Ctutorial-Pointers 1.pptCtutorial-Pointers 1.ppt
Ctutorial-Pointers 1.ppt
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 
Pointer
PointerPointer
Pointer
 
Ch8 Arrays
Ch8 ArraysCh8 Arrays
Ch8 Arrays
 
SPL_PS2 (1).ppt
SPL_PS2 (1).pptSPL_PS2 (1).ppt
SPL_PS2 (1).ppt
 
ADK COLEGE.pptx
ADK COLEGE.pptxADK COLEGE.pptx
ADK COLEGE.pptx
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptxIntroduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 

More from P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai

More from P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai (20)

TestFile
TestFileTestFile
TestFile
 
3.1 Trees ( Introduction, Binary Trees & Binary Search Trees)
3.1 Trees ( Introduction, Binary Trees & Binary Search Trees)3.1 Trees ( Introduction, Binary Trees & Binary Search Trees)
3.1 Trees ( Introduction, Binary Trees & Binary Search Trees)
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
 
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
2.2 stack applications Infix to Postfix & Evaluation of Post Fix2.2 stack applications Infix to Postfix & Evaluation of Post Fix
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
 
1. 6 doubly linked list
1. 6 doubly linked list1. 6 doubly linked list
1. 6 doubly linked list
 
1. 5 Circular singly linked list
1. 5 Circular singly linked list1. 5 Circular singly linked list
1. 5 Circular singly linked list
 
1. 4 Singly linked list deletion
1. 4 Singly linked list deletion1. 4 Singly linked list deletion
1. 4 Singly linked list deletion
 
1. 3 singly linked list insertion 2
1. 3 singly linked list   insertion 21. 3 singly linked list   insertion 2
1. 3 singly linked list insertion 2
 
1. 2 Singly Linked List
1. 2 Singly Linked List1. 2 Singly Linked List
1. 2 Singly Linked List
 
Approximation Algorithms TSP
Approximation Algorithms   TSPApproximation Algorithms   TSP
Approximation Algorithms TSP
 
Optimal binary search tree dynamic programming
Optimal binary search tree   dynamic programmingOptimal binary search tree   dynamic programming
Optimal binary search tree dynamic programming
 
The stable marriage problem iterative improvement method
The stable marriage problem iterative improvement methodThe stable marriage problem iterative improvement method
The stable marriage problem iterative improvement method
 
Maximum matching in bipartite graphs iterative improvement method
Maximum matching in bipartite graphs   iterative improvement methodMaximum matching in bipartite graphs   iterative improvement method
Maximum matching in bipartite graphs iterative improvement method
 
Knapsack dynamic programming formula top down (1)
Knapsack dynamic programming formula top down (1)Knapsack dynamic programming formula top down (1)
Knapsack dynamic programming formula top down (1)
 
Knapsack dynamic programming formula bottom up
Knapsack dynamic programming formula bottom upKnapsack dynamic programming formula bottom up
Knapsack dynamic programming formula bottom up
 
Huffman tree coding greedy approach
Huffman tree coding  greedy approachHuffman tree coding  greedy approach
Huffman tree coding greedy approach
 
Simplex method
Simplex methodSimplex method
Simplex method
 
Simplex method
Simplex methodSimplex method
Simplex method
 
Multiplication of integers &amp; strassens matrix multiplication subi notes
Multiplication of integers &amp; strassens matrix multiplication   subi notesMultiplication of integers &amp; strassens matrix multiplication   subi notes
Multiplication of integers &amp; strassens matrix multiplication subi notes
 
Multiplication of large integers problem subi notes
Multiplication of large integers  problem  subi notesMultiplication of large integers  problem  subi notes
Multiplication of large integers problem subi notes
 

Recently uploaded

Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
chumtiyababu
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 

1. C Basics for Data Structures Bridge Course

  • 1. C Basics for Data Structures Bridge Course (27.07.2020 – 31.07.2020) Dr. P. Subathra Professor Dept. of Information Technology KAMARAJ College of Engineering and Technology Madurai Tamil Nadu India subathrakishore@yahoo.com 8/14/2020
  • 2. Topics • Arrays • Pointers • Structures 8/14/2020 Functions
  • 3. Arrays 1. What is an Array? 2. How is it stored in the Memory? 3. Why isn’t there any boundary for an Array? 4. How is a program allocated memory in a system during compilation and execution? 5. What is a Pointer? 6. What actually is an Array variable? 7. How is Static Memory allocation done for an Array in C? 8. How is Dynamic Memory allocation done for an Array in C? 8/14/2020
  • 4. Arrays - Pointers 1. What is an Array? 2. How is it stored in the Memory? 3. Why isn’t there any boundary for an Array? 4. How is a program allocated memory in a system during compilation and execution? 5. What is a Pointer? 6. What is a Pointer to a Pointer? 7. What actually is an Array variable? 8. How is Static Memory allocation done for an Array in C? 9. How is Dynamic Memory allocation done for an Array in C? 8/14/2020
  • 5. Introduction • Arrays – Structures of related data items – Static entity - same size throughout program • A few types – C-like, pointer-based arrays – C++, arrays as objects
  • 6. Arrays c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Position number of the element within array c
  • 7. Declaring Arrays • Declaring arrays - specify: – Name – Type of array – Number of elements – Examples int c[ 10 ]; float hi[ 3284 ]; • Declaring multiple arrays of same type – Similar format as other variables – Example int b[ 100 ], x[ 27 ];
  • 8. Examples Using Arrays • Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 }; – If not enough initializers, rightmost elements become 0 – If too many initializers, a syntax error is generated int n[ 5 ] = { 0 } – Sets all the elements to 0 • If size omitted, the initializers determine it int n[] = { 1, 2, 3, 4, 5 }; – 5 initializers, therefore n is a 5 element array
  • 9. 9 Problem with Arrays • Sometimes – Amount of data cannot be predicted beforehand – Number of data items keeps changing during program execution • One solution: find the maximum possible value of N and allocate an array of N elements – Wasteful of memory space, as N may be much smaller in some executions – Example: maximum value of N may be 10,000, but a particular run may need to search only among 100 elements • Using array of size 10,000 always wastes memory in most cases
  • 10. 10 Better Solution • Dynamic memory allocation – Know how much memory is needed after the program is run • Example: ask the user to enter from keyboard – Dynamically allocate only the amount of memory needed • C provides functions to dynamically allocate memory – malloc, calloc, realloc
  • 11. 11 Memory Allocation Functions • malloc – Allocates requested number of bytes and returns a pointer to the first byte of the allocated space • calloc – Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. • free – Frees previously allocated space. • realloc – Modifies the size of previously allocated space.
  • 12. 12 Allocating a Block of Memory • A block of memory can be allocated using the function malloc – Reserves a block of memory of specified size and returns a pointer of type void – The return pointer can be type-casted to any pointer type • General format: type *p; p = (type *) malloc (byte_size);
  • 13. 13 Example p = (int *) malloc(100 * sizeof(int)); – A memory space equivalent to 100 times the size of an int bytes is reserved – The address of the first byte of the allocated memory is assigned to the pointer p of type int p 400 bytes of space
  • 14. 14 Contd. • cptr = (char *) malloc (20); Allocates 20 bytes of space for the pointer cptr of type char • sptr = (struct stud *) malloc(10*sizeof(struct stud)); Allocates space for a structure array of 10 elements. sptr points to a structure element of type struct stud Always use sizeof operator to find number of bytes for a data type, as it can vary from machine to machine
  • 15. 15 Points to Note • malloc always allocates a block of contiguous bytes – The allocation can fail if sufficient contiguous memory space is not available – If it fails, malloc returns NULL if ((p = (int *) malloc(100 * sizeof(int))) == NULL) { printf (“n Memory cannot be allocated”); exit(); }
  • 16. 16 Releasing the Allocated Space: free • An allocated block can be returned to the system for future use by using the free function • General syntax: free (ptr); where ptr is a pointer to a memory block which has been previously created using malloc • Note that no size needs to be mentioned for the allocated block, the system remembers it for each pointer returned
  • 34. Operations not allowed on Pointers • Addition of two pointers • Multiplication of Two pointers • Multiplying a constant to a pointer • Division of Pointers • Division of a Pointer by a Constant 8/14/2020
  • 40. Pointer to 1D Array 8/14/2020
  • 49. Pointers in 2D Arrays • Dynamic Allocation done at the HEAP 8/14/2020
  • 68. 68 Pointers to Pointers • Pointers are also variables (storing addresses), so they have a memory location, so they also have an address • Pointer to pointer – stores the address of a pointer variable int x = 10, *p, **q; p = &x; q = &p; printf(“%d %d %d”, x, *p, *(*q)); will print 10 10 10 (since *q = p)
  • 69. 69 Allocating Pointer to Pointer int **p; p = (int **) malloc(3 * sizeof(int *)); p p[2] p[1] p[0] int ** int * int * int *
  • 70. 2D array 70 #include <stdlib.h> int main() { int **array; array = (int**) malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) { array[i] = (int*)malloc(ncolumns * sizeof(int)); } {
  • 71. Arrays in C CS-2301, B-Term 2009 71 Arrays as Function Parameters • void init(float A[], int arraySize); void init(float *A, int arraySize); • Are identical function prototypes! • Pointer is passed by value • I.e. caller copies the value of a pointer to float into the parameter A • Called function can reference through that pointer to reach thing pointed to
  • 72. Arrays in C CS-2301, B-Term 2009 72 Arrays as Function Parameters (continued) • void init(float A[], int arraySize){ int n; for(n = 0; n < arraySize; n++) A[n] = (float)n; } //init • Assigns values to the array A in place – So that caller can see the changes!
  • 73. Allocating new heap memory CS 3090: Safety Critical Programming in C 73 void *malloc(size_t size); • Allocate a block of size bytes, return a pointer to the block (NULL if unable to allocate block) void *calloc(size_t num_elements, size_t element_size); • Allocate a block of num_elements * element_size bytes, initialize every byte to zero, return pointer to the block (NULL if unable to allocate block) Note: void * denotes a generic pointer type
  • 74. Allocating new heap memory CS 3090: Safety Critical Programming in C 74 void *realloc(void *ptr, size_t new_size);  Given a previously allocated block starting at ptr,  change the block size to new_size,  return pointer to resized block  If block size is increased, contents of old block may be copied to a completely different region  In this case, the pointer returned will be different from the ptr argument, and ptr will no longer point to a valid memory region  If ptr is NULL, realloc is identical to malloc  Note: may need to cast return value of malloc/calloc/realloc: char *p = (char *) malloc(BUFFER_SIZE);
  • 75. Deallocating heap memory CS 3090: Safety Critical Programming in C 75 void free(void *pointer); • Given a pointer to previously allocated memory, – put the region back in the heap of unallocated memory • Note: easy to forget to free memory when no longer needed... – especially if you’re used to a language with “garbage collection” like Java – This is the source of the notorious “memory leak” problem – Difficult to trace – the program will run fine for some time, until suddenly there is no more memory!