SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Linux Initialization Process (2)
Linux Initialization Process (2)Linux Initialization Process (2)
Linux Initialization Process (2)shimosawa
 
U-Boot presentation 2013
U-Boot presentation  2013U-Boot presentation  2013
U-Boot presentation 2013Wave Digitech
 
Profiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsProfiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsemBO_Conference
 
Building Embedded Linux Full Tutorial for ARM
Building Embedded Linux Full Tutorial for ARMBuilding Embedded Linux Full Tutorial for ARM
Building Embedded Linux Full Tutorial for ARMSherif Mousa
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New HardwareRuggedBoardGroup
 
Linux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBLinux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBshimosawa
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal BootloaderSatpal Parmar
 
Embedded_Linux_Booting
Embedded_Linux_BootingEmbedded_Linux_Booting
Embedded_Linux_BootingRashila Rr
 

Tendances (20)

C Programming - Refresher - Part I
C Programming - Refresher - Part I C Programming - Refresher - Part I
C Programming - Refresher - Part I
 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
BusyBox for Embedded Linux
BusyBox for Embedded LinuxBusyBox for Embedded Linux
BusyBox for Embedded Linux
 
Linux Internals - Part II
Linux Internals - Part IILinux Internals - Part II
Linux Internals - Part II
 
Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
 
Linux Initialization Process (2)
Linux Initialization Process (2)Linux Initialization Process (2)
Linux Initialization Process (2)
 
Linux-Internals-and-Networking
Linux-Internals-and-NetworkingLinux-Internals-and-Networking
Linux-Internals-and-Networking
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 
U-Boot presentation 2013
U-Boot presentation  2013U-Boot presentation  2013
U-Boot presentation 2013
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
Profiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf ToolsProfiling your Applications using the Linux Perf Tools
Profiling your Applications using the Linux Perf Tools
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Building Embedded Linux Full Tutorial for ARM
Building Embedded Linux Full Tutorial for ARMBuilding Embedded Linux Full Tutorial for ARM
Building Embedded Linux Full Tutorial for ARM
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
 
A practical guide to buildroot
A practical guide to buildrootA practical guide to buildroot
A practical guide to buildroot
 
Linux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKBLinux Kernel Booting Process (1) - For NLKB
Linux Kernel Booting Process (1) - For NLKB
 
Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 
Embedded_Linux_Booting
Embedded_Linux_BootingEmbedded_Linux_Booting
Embedded_Linux_Booting
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de Emertxe Information Technologies Pvt Ltd

Plus de 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
 

Dernier

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

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