SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 languagegourav kottawar
 
linux device driver
linux device driverlinux device driver
linux device driverRahul Batra
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C ProgrammingQazi Shahzad Ali
 
Data types in C language
Data types in C languageData types in C language
Data types in C languagekashyap399
 
Introduction Linux Device Drivers
Introduction Linux Device DriversIntroduction Linux Device Drivers
Introduction Linux Device DriversNEEVEE Technologies
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programmingHarshita Yadav
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 

Was ist angesagt? (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
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie C Programming - Refresher - Part III

0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdfssusere19c741
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
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 ProcessingMeghaj Mallick
 
Data structures using C
Data structures using CData structures using C
Data structures using CPdr Patnaik
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Salman Qamar
 
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 outrajatryadav22
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in CTushar B Kute
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfTamiratDejene1
 

Ähnlich wie 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
 

Mehr von Emertxe Information Technologies Pvt Ltd

Mehr von 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
 

Kürzlich hochgeladen

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 AmsterdamUiPathCommunity
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
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 connectorsNanddeep Nachan
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
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 REVIEWERMadyBayot
 
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 FMESafe Software
 
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 WorkerThousandEyes
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
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...DianaGray10
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
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 DevelopersWSO2
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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​Bhuvaneswari Subramani
 

Kürzlich hochgeladen (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
 
+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...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
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
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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​
 

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