SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
Emertxe Information Technologies Pvt Ltd
 

Mais procurados (20)

Linux Systems: Getting started with setting up an Embedded platform
Linux Systems: Getting started with setting up an Embedded platformLinux Systems: Getting started with setting up an Embedded platform
Linux Systems: Getting started with setting up an Embedded platform
 
Advanced C - Part 3
Advanced C - Part 3Advanced C - Part 3
Advanced C - Part 3
 
Embedded C
Embedded CEmbedded C
Embedded C
 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
 
Micro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application DevelopmentMicro-controllers (PIC) based Application Development
Micro-controllers (PIC) based Application Development
 
Advanced C
Advanced C Advanced C
Advanced C
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
 
Embedded Linux Kernel - Build your custom kernel
Embedded Linux Kernel - Build your custom kernelEmbedded Linux Kernel - Build your custom kernel
Embedded Linux Kernel - Build your custom kernel
 
Linux device drivers
Linux device drivers Linux device drivers
Linux device drivers
 
Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
linux device driver
linux device driverlinux device driver
linux device driver
 
Getting started with BeagleBone Black - Embedded Linux
Getting started with BeagleBone Black - Embedded LinuxGetting started with BeagleBone Black - Embedded Linux
Getting started with BeagleBone Black - Embedded Linux
 
Introduction to char device driver
Introduction to char device driverIntroduction to char device driver
Introduction to char device driver
 
BusyBox for Embedded Linux
BusyBox for Embedded LinuxBusyBox for Embedded Linux
BusyBox for Embedded Linux
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 
Embedded C - Day 1
Embedded C - Day 1Embedded C - Day 1
Embedded C - Day 1
 
Embedded Android : System Development - Part III
Embedded Android : System Development - Part IIIEmbedded Android : System Development - Part III
Embedded Android : System Development - Part III
 
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
 

Destaque

Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowcharts
kapil078
 
Protein Structure & Function
Protein Structure & FunctionProtein Structure & Function
Protein Structure & Function
iptharis
 
Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowcharts
nicky_walters
 

Destaque (15)

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

Semelhante a C Programming - Refresher - Part III

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

Semelhante a 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
 

Mais de Emertxe Information Technologies Pvt Ltd

Mais 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
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+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@
 
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
panagenda
 

Último (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
+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...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
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
 
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, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

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