SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
 
Embedded C - Day 1
Embedded C - Day 1Embedded C - Day 1
Embedded C - Day 1
 
Advanced C - Part 3
Advanced C - Part 3Advanced C - Part 3
Advanced C - Part 3
 
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 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 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
 
Linux-Internals-and-Networking
Linux-Internals-and-NetworkingLinux-Internals-and-Networking
Linux-Internals-and-Networking
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
A practical guide to buildroot
A practical guide to buildrootA practical guide to buildroot
A practical guide to buildroot
 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
 
Embedded C programming session10
Embedded C programming  session10Embedded C programming  session10
Embedded C programming session10
 
Linux Internals - Interview essentials 4.0
Linux Internals - Interview essentials 4.0Linux Internals - Interview essentials 4.0
Linux Internals - Interview essentials 4.0
 
Embedded C - Lecture 3
Embedded C - Lecture 3Embedded C - Lecture 3
Embedded C - Lecture 3
 
Linux programming - Getting self started
Linux programming - Getting self started Linux programming - Getting self started
Linux programming - Getting self started
 
BusyBox for Embedded Linux
BusyBox for Embedded LinuxBusyBox for Embedded Linux
BusyBox for Embedded Linux
 
Embedded C - Lecture 4
Embedded C - Lecture 4Embedded C - Lecture 4
Embedded C - Lecture 4
 
Introduction to Embedded Systems
Introduction to Embedded Systems Introduction to Embedded Systems
Introduction to Embedded Systems
 
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)
 

Destacado

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
 

Destacado (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
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
Linux device drivers
Linux device drivers Linux device drivers
Linux device drivers
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basics
 
Protein Structure & Function
Protein Structure & FunctionProtein Structure & Function
Protein Structure & Function
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Flowchart pseudocode-examples
Flowchart pseudocode-examplesFlowchart pseudocode-examples
Flowchart pseudocode-examples
 
Pseudocode flowcharts
Pseudocode flowchartsPseudocode flowcharts
Pseudocode flowcharts
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
 
C Basics
C BasicsC Basics
C Basics
 

Similar a C Programming - Refresher - Part III

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

Similar 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
 

Más de Emertxe Information Technologies Pvt Ltd

Más 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

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+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@
 

Último (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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
 
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
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

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