SlideShare a Scribd company logo
1 of 39
Download to read offline
Embedded C ā€“ Part III
Pointers
Team Emertxe
Pointers : Sharp Knives
Handle with Care!
Pointers : Why
ā— To have C as a low level language being a high level language.
ā— To have the dynamic allocation mechanism.
ā— To achieve the similar results as of ā€pass by variableā€
parameter passing mechanism in function, by passing the reference.
ā— Returning more than one value in a function.
Pointers & Seven rules
Rule #1
Pointer as a integer variable
Example
Syntax
dataType *pointer_name;
Pictorial Representation
10
a
100
100
200
p
DIY:
Declare the float pointer & assign the address of float variable
Rule #2
Referencing & Dereferencing
Example
DIY:
Print the value of double using the pointer.
Variable Address
Referencing
De-Referencing
&
*
Rule #3
Type of a pointer
All pointers are of same size.
l
Pointer of type t t Pointer (t *) A variable which contains anā‰” ā‰” ā‰”
address,which when dereferenced becomes a variable of type t
Rule #4
Value of a pointer
Example
Pictorial Representation
10
a
100
100
200
p
Pointing means Containing
l
Pointer pointing to a variable ā‰”
l
Pointer contains the address of the
variable
Rule #5
NULL pointer
Example
Pictorial Representation
NULL
200
p
Not pointing to anywhere
l
Pointer Value of zero Null Addr NULLā‰” ā‰”
pointer Pointing to nothingā‰”
Segmentation fault
A segmentation fault occurs when a program attempts to access a memory location
that it is not allowed to access, or attempts to access a memory location in a way
that is not allowed.
Example
Fault occurs, while attempting to write to a read-only
location, or to overwrite part of the operating system
Bus error
A bus error is a fault raised by hardware, notifying an operating system (OS) that a
process is trying to access memory that the CPU cannot physically address: an
invalid address for the address bus, hence the name.
Example
DIY: Write a similar code which creates bus error
Rule #6:
Arithmetic Operations with Pointers & Arrays
l
value(p + i) value(p) + value(i) * sizeof(*p)ā‰”
l
Array Collection of variables vs Constant pointer variableā†’
l
short sa[10];
l
&sa Address of the array variableā†’
l
sa[0] First elementā†’
l
&sa[0] Address of the first array elementā†’
l
sa Constant pointer variableā†’
l
Arrays vs Pointers
l
Commutative use
l
(a + i) i + a &a[i] &i[a]ā‰” ā‰” ā‰”
l
*(a + i) *(i + a) a[i] i[a]ā‰” ā‰” ā‰”
l
constant vs variable
Rule #7:
Static & Dynamic Allocation
l
Static Allocation Named Allocation -ā‰”
l
Compilerā€™s responsibility to manage it ā€“ Done internally by compiler,
l
when variables are defined
l
Dynamic Allocation Unnamed Allocation -ā‰”
l
Userā€™s responsibility to manage it ā€“ Done using malloc & free
l
Differences at program segment level
l
Defining variables (data & stack segmant) vs Getting & giving it from
l
the heap segment using malloc & free
l
int x, int *xp, *ip;
l
xp = &x;
l
ip = (int*)(malloc(sizeof(int)));
Pointers: Big Picture
Pointers: Big Picture
Pointers :
Simple data Types
l
'A'
100 101 102 104 105 . . .
100
chcptr
200
'A'
100 101 102 104 105 . . .
100
chcptr
200
100 101 102 104 105 . . .
100
iiptr
200
Pointers :
Compound data Types
Example: Arrays & Strings (1D arrays)
int age[ 5 ] = {10, 20, 30, 40, 50};
int *p = age;
Memory Allocation
10 20 30 40 50
age[0]
age[4]
age[3]
age[2]
age[1]
100 104 108 112 116
ļƒ¼
DIY : Write a program to add all the elements of the array.
100
p
age[i] ā‰” *(age + i)
i[age] ā‰” *(i + age)
ā‰”
ā‰”
age[2] = *(age + 2) = *(age + 2 * sizeof(int))
= *(age + 2 * 4)
= *(100 + 2 * 4)
= *(108)
= 30 = *(p + 2) = p[2]
Pointers :
Compound data Types
Example: Arrays & Strings (2D arrays)
int a[ 3 ][ 2 ] = {10, 20, 30, 40, 50, 60};
int ( * p) [ 2 ] = a;
Memory Allocation
p
10 20
30 40
50 60
Pointers :
Compound data Types
Example: Arrays & Strings (2D arrays)
int a[ 3 ][ 2 ] = {10, 20, 30, 40, 50, 60};
int ( * p) [ 2 ] = a;
ļƒ¼
DIY : Write a program to print all the elements of the
ļƒ¼
2D array.
a[2][1] = *(*(age + 2) + 1) = *(*(a + 2 * sizeof(1D array)) + 1 * sizeof(int))
= *(*(a + 2 * 8) + 1 * 4)
= *(*(100 + 2 * 8) + 4)
= *(*(108) + 4)
= *(108 + 4)
= *(112)
= 40 = p[2][1]
In general :
a[i][j] ā‰” *(a[i] + j) ā‰” *(*(a + i) + j) ā‰” (*(a + i))[j] ā‰” j[a[i]] ā‰” j[i[a]] ā‰” j[*(a + i)]
Dynamic Memory Allocation
l
In C functions for dynamic memory allocation functions are
l
declared in the header file <stdlib.h>.
l
In some implementations, it might also be provided
l
in <alloc.h> or <malloc.h>.
ā— malloc
ā— calloc
ā— realloc
ā— free
Malloc
l
The malloc function allocates a memory block of size size from dynamic
l
memory and returns pointer to that block if free space is available, other
l
wise it returns a null pointer.
l
Prototype
l
void *malloc(size_t size);
calloc
l
The calloc function returns the memory (all initialized to zero)
l
so may be handy to you if you want to make sure that the memory
l
is properly initialized.
l
calloc can be considered as to be internally implemented using
l
malloc (for allocating the memory dynamically) and later initialize
l
the memory block (with the function, say, memset()) to initialize it to zero.
l
Prototype
l
void *calloc(size_t n, size_t size);
Realloc
l
The function realloc has the following capabilities
l
1. To allocate some memory (if p is null, and size is non-zero,
l
then it is same as malloc(size)),
l
2. To extend the size of an existing dynamically allocated block
l
(if size is bigger than the existing size of the block pointed by p),
l
3. To shrink the size of an existing dynamically allocated block
l
(if size is smaller than the existing size of the block pointed by p),
l
4. To release memory (if size is 0 and p is not NULL
l
then it acts like free(p)).
l
Prototype
l
void *realloc(void *ptr, size_t size);
free
l
The free function assumes that the argument given is a pointer to the memory
l
that is to be freed and performs no heck to verify that memory has already
l
been allocated.
l
1. if free() is called on a null pointer, nothing happens.
l
2. if free() is called on pointer pointing to block other
l
than the one allocated by dynamic allocation, it will lead to
l
undefined behavior.
l
3. if free() is called with invalid argument that may collapse
l
the memory management mechanism.
l
4. if free() is not called on the dynamically allocated memory block
l
after its use, it will lead to memory leaks.
l
Prototype
l
void free(void *ptr);
2D Arrays
ļƒ¼Each Dimension could be static or Dynamic
ļƒ¼Various combinations for 2-D Arrays (2x2 = 4)
ā€¢ C1: Both Static (Rectangular)
ā€¢ C2: First Static, Second Dynamic
ā€¢ C3: First Dynamic, Second Static
ā€¢ C4: Both Dynamic
ļƒ¼2-D Arrays using a Single Level Pointer
C1: Both static
ļƒ¼Rectangular array
ļƒ¼int rec [5][6];
ļƒ¼Takes totally 5 * 6 * sizeof(int) bytes
Static
Static
C2: First static,
Second dynamic
ļƒ¼ One dimension static, one dynamic (Mix of Rectangular & Ragged)
int *ra[5];
for( i = 0; i < 5; i++)
ra[i] = (int*) malloc( 6 * sizeof(int));
ļƒ¼Total memory used : 5 * sizeof(int *) + 6 * 5 * sizeof(int) bytes
Static
Dynamic
C2: First static,
Second dynamic
ļƒ¼ One dimension static, one dynamic (Mix of Rectangular & Ragged)
int *ra[5];
for( i = 0; i < 5; i++)
ra[i] = (int*) malloc( 6 * sizeof(int));
ļƒ¼Total memory used : 5 * sizeof(int *) + 6 * 5 * sizeof(int) bytes
Static
Dynamic
C3: Second static,
First dynamic
ļƒ¼One static, One dynamic
int (*ra)[6]; (Pointer to array of 6 integer)
ra = (int(*)[6]) malloc( 5 * sizeof(int[6]));
ļƒ¼Total memory used : sizeof(int *) + 6 * 5 * sizeof(int) bytes
Static
ra
C4: Both dynamic
ļƒ¼Ragged array
int **ra;
ra = (int **) malloc (5 * sizeof(int*));
for(i = 0; i < 5; i++)
ra[i] = (int*) malloc( 6 * sizeof(int));
ļƒ¼Takes 5 * sizeof(int*) for first level of indirection
ļƒ¼Total memory used : 1 * sizeof(int **) + 5 * sizeof(int *) + 5 * 6 *
sizeof(int) bytes
ra[0]
ra[1]
ra[2]
ra[3]
ra[4]
ra
Function Pointers
Function pointers : Why
l
ā— Chunk of code that can be called independently and is standalone
ā— Independent code that can be used to iterate over a collection of
objects
ā— Event management which is essentially asynchronous where there
may be several objects that may be interested in ā€Listeningā€ such
an event
ā— ā€Registeringā€ a piece of code and calling it later when required.
Function Pointers:
Declaration
Syntax
return_type (*ptr_name)(type1, type2, type3, ...)
Example
float (*fp)( int );
Description:
fp is a pointer that can point to any function that returns a float value and accepts an int as
an argument.
Function Pointers:
Example
Function Pointers:
As an argument
Function Pointers:
More examples
ā— The bsearch function in the standard header file <stdlib.h>
void *bsearch(void *key, void *base, size_t num, size_t width,
int (*compare)(void *elem1, void *elem2));
ā— The last parameter is a function pointer.
ā— It points to a function that can compare two elements (of the sorted array, pointed by
base) and return an int as a result.
ā— This serves as general method for the usage of function pointers. The bsearch function
does not know anything about the elements in the array and so it cannot decide how to
compare the elements in the array.
ā— To make a decision on this, we should have a separately function for it and pass it to
bsearch.
ā— Whenever bsearch needs to compare, it will call this function to do it. This is a simple
usage of function pointers as callback methods.
Function Pointers:
More examples
ā— Function pointers can be registered & can be called when the program exits
Output ?
Stay connected
About us: Emertxe is Indiaā€™s one of the top IT finishing schools & self learning
kits provider. Our primary focus is on Embedded with diversification focus on
Java, Oracle and Android areas
Branch Office: Corporate Headquarters:
Emertxe Information Technologies, Emertxe Information Technologies,
No-1, 9th Cross, 5th Main, 83, Farah Towers, 1st
Floor,
Jayamahal Extension, MG Road,
Bangalore, Karnataka 560046 Bangalore, Karnataka - 560001
T:Ā +91 809 555 7333 (M), +91 80 41289576 (L)
E: training@emertxe.com
https://www.facebook.com/Emertxe https://twitter.com/EmertxeTweet https://www.slideshare.net/EmertxeSlides
THANK YOU

More Related Content

What's hot

Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
Emertxe Information Technologies Pvt Ltd
Ā 
Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
Ā 

What's hot (20)

detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
Ā 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
Ā 
Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
Ā 
Embedded C - Lecture 3
Embedded C - Lecture 3Embedded C - Lecture 3
Embedded C - Lecture 3
Ā 
linux device driver
linux device driverlinux device driver
linux device driver
Ā 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Ā 
Linux Internals - Part II
Linux Internals - Part IILinux Internals - Part II
Linux Internals - Part II
Ā 
Functions in c
Functions in cFunctions in c
Functions in c
Ā 
Linux-Internals-and-Networking
Linux-Internals-and-NetworkingLinux-Internals-and-Networking
Linux-Internals-and-Networking
Ā 
Data types in C language
Data types in C languageData types in C language
Data types in C language
Ā 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
Ā 
I2c drivers
I2c driversI2c drivers
I2c drivers
Ā 
A practical guide to buildroot
A practical guide to buildrootA practical guide to buildroot
A practical guide to buildroot
Ā 
Micro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application DevelopmentMicro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application Development
Ā 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
Ā 
Enums in c
Enums in cEnums in c
Enums in c
Ā 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
Ā 
Introduction Linux Device Drivers
Introduction Linux Device DriversIntroduction Linux Device Drivers
Introduction Linux Device Drivers
Ā 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
Ā 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
Ā 

Viewers also liked

Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowcharts
kapil078
Ā 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
Durga Padma
Ā 
Protein Structure & Function
Protein Structure & FunctionProtein Structure & Function
Protein Structure & Function
iptharis
Ā 
Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowcharts
nicky_walters
Ā 

Viewers also liked (16)

C Programming - Refresher - Part IV
C Programming - Refresher - Part IVC Programming - Refresher - Part IV
C Programming - Refresher - Part IV
Ā 
Embedded C - Optimization techniques
Embedded C - Optimization techniquesEmbedded C - Optimization techniques
Embedded C - Optimization techniques
Ā 
best notes in c language
best notes in c languagebest notes in c language
best notes in c language
Ā 
Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowcharts
Ā 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
Ā 
Data Structures & Algorithm design using C
Data Structures & Algorithm design using C Data Structures & Algorithm design using C
Data Structures & Algorithm design using C
Ā 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
Ā 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
Ā 
Linux device drivers
Linux device drivers Linux device drivers
Linux device drivers
Ā 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basics
Ā 
Protein Structure & Function
Protein Structure & FunctionProtein Structure & Function
Protein Structure & Function
Ā 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
Ā 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examples
Ā 
Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowcharts
Ā 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
Ā 
C Basics
C BasicsC Basics
C Basics
Ā 

Similar to C Programming - Refresher - Part III

Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
tech4us
Ā 

Similar to C Programming - Refresher - Part III (20)

Pointers
PointersPointers
Pointers
Ā 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
Ā 
Python
PythonPython
Python
Ā 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
Ā 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Ā 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
Ā 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
Ā 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Ā 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
Ā 
Data structures using C
Data structures using CData structures using C
Data structures using C
Ā 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02
Ā 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
Ā 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Ā 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
Ā 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Ā 
See through C
See through CSee through C
See through C
Ā 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
Ā 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
Ā 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in C
Ā 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
Ā 

More from Emertxe Information Technologies Pvt Ltd

More from Emertxe Information Technologies Pvt Ltd (20)

premium post (1).pdf
premium post (1).pdfpremium post (1).pdf
premium post (1).pdf
Ā 
Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Ā 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
Ā 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
Ā 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
Ā 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
Ā 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
Ā 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
Ā 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
Ā 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
Ā 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
Ā 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
Ā 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
Ā 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
Ā 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
Ā 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
Ā 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
Ā 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
Ā 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
Ā 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
Ā 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(ā˜Žļø+971_581248768%)**%*]'#abortion pills for sale in dubai@
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
Ā 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
Ā 

Recently uploaded (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
Ā 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
Ā 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
Ā 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Ā 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
Ā 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
Ā 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
Ā 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Ā 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
Ā 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Ā 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
Ā 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Ā 
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Ā 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
Ā 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Ā 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
Ā 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
Ā 

C Programming - Refresher - Part III

  • 1. Embedded C ā€“ Part III Pointers Team Emertxe
  • 2. Pointers : Sharp Knives Handle with Care!
  • 3. Pointers : Why ā— To have C as a low level language being a high level language. ā— To have the dynamic allocation mechanism. ā— To achieve the similar results as of ā€pass by variableā€ parameter passing mechanism in function, by passing the reference. ā— Returning more than one value in a function.
  • 5. Rule #1 Pointer as a integer variable Example Syntax dataType *pointer_name; Pictorial Representation 10 a 100 100 200 p DIY: Declare the float pointer & assign the address of float variable
  • 6. Rule #2 Referencing & Dereferencing Example DIY: Print the value of double using the pointer. Variable Address Referencing De-Referencing & *
  • 7. Rule #3 Type of a pointer All pointers are of same size. l Pointer of type t t Pointer (t *) A variable which contains anā‰” ā‰” ā‰” address,which when dereferenced becomes a variable of type t
  • 8. Rule #4 Value of a pointer Example Pictorial Representation 10 a 100 100 200 p Pointing means Containing l Pointer pointing to a variable ā‰” l Pointer contains the address of the variable
  • 9. Rule #5 NULL pointer Example Pictorial Representation NULL 200 p Not pointing to anywhere l Pointer Value of zero Null Addr NULLā‰” ā‰” pointer Pointing to nothingā‰”
  • 10. Segmentation fault A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed. Example Fault occurs, while attempting to write to a read-only location, or to overwrite part of the operating system
  • 11. Bus error A bus error is a fault raised by hardware, notifying an operating system (OS) that a process is trying to access memory that the CPU cannot physically address: an invalid address for the address bus, hence the name. Example DIY: Write a similar code which creates bus error
  • 12. Rule #6: Arithmetic Operations with Pointers & Arrays l value(p + i) value(p) + value(i) * sizeof(*p)ā‰” l Array Collection of variables vs Constant pointer variableā†’ l short sa[10]; l &sa Address of the array variableā†’ l sa[0] First elementā†’ l &sa[0] Address of the first array elementā†’ l sa Constant pointer variableā†’ l Arrays vs Pointers l Commutative use l (a + i) i + a &a[i] &i[a]ā‰” ā‰” ā‰” l *(a + i) *(i + a) a[i] i[a]ā‰” ā‰” ā‰” l constant vs variable
  • 13. Rule #7: Static & Dynamic Allocation l Static Allocation Named Allocation -ā‰” l Compilerā€™s responsibility to manage it ā€“ Done internally by compiler, l when variables are defined l Dynamic Allocation Unnamed Allocation -ā‰” l Userā€™s responsibility to manage it ā€“ Done using malloc & free l Differences at program segment level l Defining variables (data & stack segmant) vs Getting & giving it from l the heap segment using malloc & free l int x, int *xp, *ip; l xp = &x; l ip = (int*)(malloc(sizeof(int)));
  • 16. Pointers : Simple data Types l 'A' 100 101 102 104 105 . . . 100 chcptr 200 'A' 100 101 102 104 105 . . . 100 chcptr 200 100 101 102 104 105 . . . 100 iiptr 200
  • 17. Pointers : Compound data Types Example: Arrays & Strings (1D arrays) int age[ 5 ] = {10, 20, 30, 40, 50}; int *p = age; Memory Allocation 10 20 30 40 50 age[0] age[4] age[3] age[2] age[1] 100 104 108 112 116 ļƒ¼ DIY : Write a program to add all the elements of the array. 100 p age[i] ā‰” *(age + i) i[age] ā‰” *(i + age) ā‰” ā‰” age[2] = *(age + 2) = *(age + 2 * sizeof(int)) = *(age + 2 * 4) = *(100 + 2 * 4) = *(108) = 30 = *(p + 2) = p[2]
  • 18. Pointers : Compound data Types Example: Arrays & Strings (2D arrays) int a[ 3 ][ 2 ] = {10, 20, 30, 40, 50, 60}; int ( * p) [ 2 ] = a; Memory Allocation p 10 20 30 40 50 60
  • 19. Pointers : Compound data Types Example: Arrays & Strings (2D arrays) int a[ 3 ][ 2 ] = {10, 20, 30, 40, 50, 60}; int ( * p) [ 2 ] = a; ļƒ¼ DIY : Write a program to print all the elements of the ļƒ¼ 2D array. a[2][1] = *(*(age + 2) + 1) = *(*(a + 2 * sizeof(1D array)) + 1 * sizeof(int)) = *(*(a + 2 * 8) + 1 * 4) = *(*(100 + 2 * 8) + 4) = *(*(108) + 4) = *(108 + 4) = *(112) = 40 = p[2][1] In general : a[i][j] ā‰” *(a[i] + j) ā‰” *(*(a + i) + j) ā‰” (*(a + i))[j] ā‰” j[a[i]] ā‰” j[i[a]] ā‰” j[*(a + i)]
  • 20. Dynamic Memory Allocation l In C functions for dynamic memory allocation functions are l declared in the header file <stdlib.h>. l In some implementations, it might also be provided l in <alloc.h> or <malloc.h>. ā— malloc ā— calloc ā— realloc ā— free
  • 21. Malloc l The malloc function allocates a memory block of size size from dynamic l memory and returns pointer to that block if free space is available, other l wise it returns a null pointer. l Prototype l void *malloc(size_t size);
  • 22. calloc l The calloc function returns the memory (all initialized to zero) l so may be handy to you if you want to make sure that the memory l is properly initialized. l calloc can be considered as to be internally implemented using l malloc (for allocating the memory dynamically) and later initialize l the memory block (with the function, say, memset()) to initialize it to zero. l Prototype l void *calloc(size_t n, size_t size);
  • 23. Realloc l The function realloc has the following capabilities l 1. To allocate some memory (if p is null, and size is non-zero, l then it is same as malloc(size)), l 2. To extend the size of an existing dynamically allocated block l (if size is bigger than the existing size of the block pointed by p), l 3. To shrink the size of an existing dynamically allocated block l (if size is smaller than the existing size of the block pointed by p), l 4. To release memory (if size is 0 and p is not NULL l then it acts like free(p)). l Prototype l void *realloc(void *ptr, size_t size);
  • 24. free l The free function assumes that the argument given is a pointer to the memory l that is to be freed and performs no heck to verify that memory has already l been allocated. l 1. if free() is called on a null pointer, nothing happens. l 2. if free() is called on pointer pointing to block other l than the one allocated by dynamic allocation, it will lead to l undefined behavior. l 3. if free() is called with invalid argument that may collapse l the memory management mechanism. l 4. if free() is not called on the dynamically allocated memory block l after its use, it will lead to memory leaks. l Prototype l void free(void *ptr);
  • 25. 2D Arrays ļƒ¼Each Dimension could be static or Dynamic ļƒ¼Various combinations for 2-D Arrays (2x2 = 4) ā€¢ C1: Both Static (Rectangular) ā€¢ C2: First Static, Second Dynamic ā€¢ C3: First Dynamic, Second Static ā€¢ C4: Both Dynamic ļƒ¼2-D Arrays using a Single Level Pointer
  • 26. C1: Both static ļƒ¼Rectangular array ļƒ¼int rec [5][6]; ļƒ¼Takes totally 5 * 6 * sizeof(int) bytes Static Static
  • 27. C2: First static, Second dynamic ļƒ¼ One dimension static, one dynamic (Mix of Rectangular & Ragged) int *ra[5]; for( i = 0; i < 5; i++) ra[i] = (int*) malloc( 6 * sizeof(int)); ļƒ¼Total memory used : 5 * sizeof(int *) + 6 * 5 * sizeof(int) bytes Static Dynamic
  • 28. C2: First static, Second dynamic ļƒ¼ One dimension static, one dynamic (Mix of Rectangular & Ragged) int *ra[5]; for( i = 0; i < 5; i++) ra[i] = (int*) malloc( 6 * sizeof(int)); ļƒ¼Total memory used : 5 * sizeof(int *) + 6 * 5 * sizeof(int) bytes Static Dynamic
  • 29. C3: Second static, First dynamic ļƒ¼One static, One dynamic int (*ra)[6]; (Pointer to array of 6 integer) ra = (int(*)[6]) malloc( 5 * sizeof(int[6])); ļƒ¼Total memory used : sizeof(int *) + 6 * 5 * sizeof(int) bytes Static ra
  • 30. C4: Both dynamic ļƒ¼Ragged array int **ra; ra = (int **) malloc (5 * sizeof(int*)); for(i = 0; i < 5; i++) ra[i] = (int*) malloc( 6 * sizeof(int)); ļƒ¼Takes 5 * sizeof(int*) for first level of indirection ļƒ¼Total memory used : 1 * sizeof(int **) + 5 * sizeof(int *) + 5 * 6 * sizeof(int) bytes ra[0] ra[1] ra[2] ra[3] ra[4] ra
  • 32. Function pointers : Why l ā— Chunk of code that can be called independently and is standalone ā— Independent code that can be used to iterate over a collection of objects ā— Event management which is essentially asynchronous where there may be several objects that may be interested in ā€Listeningā€ such an event ā— ā€Registeringā€ a piece of code and calling it later when required.
  • 33. Function Pointers: Declaration Syntax return_type (*ptr_name)(type1, type2, type3, ...) Example float (*fp)( int ); Description: fp is a pointer that can point to any function that returns a float value and accepts an int as an argument.
  • 36. Function Pointers: More examples ā— The bsearch function in the standard header file <stdlib.h> void *bsearch(void *key, void *base, size_t num, size_t width, int (*compare)(void *elem1, void *elem2)); ā— The last parameter is a function pointer. ā— It points to a function that can compare two elements (of the sorted array, pointed by base) and return an int as a result. ā— This serves as general method for the usage of function pointers. The bsearch function does not know anything about the elements in the array and so it cannot decide how to compare the elements in the array. ā— To make a decision on this, we should have a separately function for it and pass it to bsearch. ā— Whenever bsearch needs to compare, it will call this function to do it. This is a simple usage of function pointers as callback methods.
  • 37. Function Pointers: More examples ā— Function pointers can be registered & can be called when the program exits Output ?
  • 38. Stay connected About us: Emertxe is Indiaā€™s one of the top IT finishing schools & self learning kits provider. Our primary focus is on Embedded with diversification focus on Java, Oracle and Android areas Branch Office: Corporate Headquarters: Emertxe Information Technologies, Emertxe Information Technologies, No-1, 9th Cross, 5th Main, 83, Farah Towers, 1st Floor, Jayamahal Extension, MG Road, Bangalore, Karnataka 560046 Bangalore, Karnataka - 560001 T:Ā +91 809 555 7333 (M), +91 80 41289576 (L) E: training@emertxe.com https://www.facebook.com/Emertxe https://twitter.com/EmertxeTweet https://www.slideshare.net/EmertxeSlides