SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
See through C
Module 2
Pointers
Tushar B Kute
http://tusharkute.com
Objectives
Be able to use arrays, pointers, and strings in
C programs
Be able to explain the representation of these
data types at the machine level, including
their similarities and differences
http://www.tusharkute.com 2
http://www.tusharkute.com 3
Arrays in C
No bounds checking!
Allowed – usually causes no error
array[10] may overwrite b
Unlike Java, array size in declaration
int array[10];
int b;
array[0] = 3;
array[9] = 4;
array[10] = 5;
array[-1] = 6;
Compare: C: int array[10];
Java: int[] array = new int[10];
All elements of same type – homogenous
First element (index 0)
Last element (index size - 1)
http://www.tusharkute.com 4
Array Representation
Homogeneous → Each element same size – s bytes
 An array of m data values is a sequence of m×s bytes
 Indexing: 0th value at byte s×0, 1st value at byte s×1, …
m and s are not part of representation
 Unlike in some other languages
 s known by compiler – usually irrelevant to programmer
 m often known by compiler – if not, must be saved by
programmer
a[0]
a[1]
a[2]
0x1000
0x1004
0x1008
int a[3];
http://www.tusharkute.com 5
Array Representation
char c1;
int a[3];
char c2;
int i;
c1
a[0]
a[1]
a[2]
i
0x1000
0x1004
0x1008
0x100C
0x1014
c20x1010
Could be optimized
by making these
adjacent, and
reducing padding
(by default, not)
Array aligned by
size of elements
http://www.tusharkute.com 6
Array Sizes
What is
sizeof(array[3])?
sizeof(array)?
int array[10];
4
40
returns the size of
an object in bytes
http://www.tusharkute.com 7
Multi-Dimensional Arrays
int matrix[2][3];
matrix[1][0] = 17;
matrix[0][0]
matrix[0][1]
matrix[0][2]
0x1000
0x1004
0x1008
matrix[1][0]
matrix[1][1]
matrix[1][2]
0x100C
0x1010
0x1014
Recall: no bounds checking
What happens when you write:
matrix[0][3] = 42;
“Row Major”
Organization
http://www.tusharkute.com 8
Sample Program
#include<stdio.h>
int main()
{
int arr[10], c;
printf(“Enter 10 elements: “);
for(c=0;c<10;c++)
scanf(“%d”,&arr[c]);
printf(“Array elements are: “);
for(c=0;c<10;c++)
printf(“n%d”,arr[c]);
}
http://www.tusharkute.com 9
Exercise Programs
Program-1
 Write a program to input 10 elements from user
and find addition of all the numbers.
Program-2
 Write a program to input 5 numbers from keyboard
and find greatest among all the elements.
Program-3
 Write a program input 10 array elements and
separate odd and even numbers from the array.
http://www.tusharkute.com 10
Memory Addresses
Storage cells are typically viewed as being
byte-sized
 Usually the smallest addressable unit of memory
• Few machines can directly address bits individually
 Such addresses are sometimes called
byte-addresses
Memory is often accessed as words
 Usually a word is the largest unit of memory access
by a single machine instruction
• CLEAR’s word size is 8 bytes (= sizeof(long))
 A word-address is simply the byte-address of the
word’s first byte
http://www.tusharkute.com 11
Pointers
Why Pointers?
Advantages?
Disadvantages?
http://www.tusharkute.com 12
Pointers
Special case of bounded-size natural numbers
 Maximum memory limited by processor word-size
 232 bytes = 4GB, 264 bytes = 16 exabytes
A pointer is just another kind of value
 A basic type in C
int *ptr;
The variable “ptr” is a pointer to an “int”.
http://www.tusharkute.com 13
Pointer Operations in C
Creation
& variable Returns variable’s memory address
Dereference
* pointer Returns contents stored at address
Indirect assignment
* pointer = val Stores value at address
Of course, still have...
Assignment
pointer = ptr Stores pointer in another variable
http://www.tusharkute.com 14
Using Pointers
int i1;
int i2;
int *ptr1;
int *ptr2;
i1 = 1;
i2 = 2;
ptr1 = &i1;
ptr2 = ptr1;
*ptr1 = 3;
i2 = *ptr2;
i1:
i2:
ptr1:
0x1000
0x1004
0x1008
…
ptr2:
…
0x100C
0x1010
0x1014
1
2
0x1000
0x1000
3
3
http://www.tusharkute.com 15
Using Pointers (cont.)
Type check warning: int_ptr2 is not an int
int1 becomes 8
int int1 = 1036; /* some data to point to */
int int2 = 8;
int *int_ptr1 = &int1; /* get addresses of data */
int *int_ptr2 = &int2;
*int_ptr1 = int_ptr2;
*int_ptr1 = int2;
What happens?
http://www.tusharkute.com 16
Using Pointers (cont.)
Type check warning: *int_ptr2 is not an int *
Changes int_ptr1 – doesn’t change int1
int int1 = 1036; /* some data to point to */
int int2 = 8;
int *int_ptr1 = &int1; /* get addresses of data */
int *int_ptr2 = &int2;
int_ptr1 = *int_ptr2;
int_ptr1 = int_ptr2;
What happens?
http://www.tusharkute.com 17
Pointer Arithmetic
pointer + number pointer – number
E.g., pointer + 1 adds 1 something to a pointer
char *p;
char a;
char b;
p = &a;
p += 1;
int *p;
int a;
int b;
p = &a;
p += 1;In each, p now points to b
(Assuming compiler doesn’t
reorder variables in memory)
Adds 1*sizeof(char) to
the memory address
Adds 1*sizeof(int) to
the memory address
Pointer arithmetic should be used cautiously
http://www.tusharkute.com 18
The Simplest Pointer in C
Special constant pointer NULL
 Points to no data
 Dereferencing illegal – causes segmentation fault
 To define, include <stdlib.h> or <stdio.h>
http://www.tusharkute.com 19
Generic Pointers
void *: a “pointer to anything”
Lose all information about what type of thing
is pointed to
 Reduces effectiveness of compiler’s type-checking
 Can’t use pointer arithmetic
void *p;
int i;
char c;
p = &i;
p = &c;
putchar(*(char *)p);
type cast: tells the compiler to
“change” an object’s type (for
type checking purposes – does
not modify the object in any way)
Dangerous! Sometimes
necessary…
http://www.tusharkute.com 20
Pass-by-Reference
void
set_x_and_y(int *x,
int *y)
{
*x = 1001;
*y = 1002;
}
void
f(void)
{
int a = 1;
int b = 2;
set_x_and_y(&a,&b);
}
1
2
a
b
x
y
1001
1002
http://www.tusharkute.com 21
Arrays and Pointers
Dirty “secret”:
Array ≈ pointer to the initial
(0th) array element
a[i] ≡ *(a+i)
An array is passed to a function
as a pointer
 The array size is lost!
Usually bad style to interchange
arrays and pointers
 Avoid pointer arithmetic!
Really int *array
int
foo(int array[],
unsigned int size)
{
… array[size - 1] …
}
int
main(void)
{
int a[10], b[5];
… foo(a, 10)… foo(b, 5) …
}
Must explicitly
pass the size
Passing arrays:
http://www.tusharkute.com 22
Arrays and Pointers
int a[]={4,5,1,2,8,9,3,0,7,6};
int *p, i;
p = a; // points first element.
//p = &a[0];
printf("nArray elements are: n");
for(i=0;i<10;i++)
{
printf(" %dn", *p);
p++;
}
http://www.tusharkute.com 23
Passing arrays to functions
Arrays can be passed to the functions as
parameters.
In such cases the arrays and pointers are not
differentiated.
e.g.
int print(int *a, int c)
{
int i;
for(i=0;i<c;i++,a++)
printf("%dn",*a);
}
http://www.tusharkute.com 24
Returning pointers from functions
Pointer can be the return type of the function.
It is used for returning multiple values from
function.
e.g.
int * increment(int *a, int c)
{
int i, *p;
p = a;
for(i=0;i<c;i++,a++)
*a = *a + 1;
return p;
}
http://www.tusharkute.com 25
Call by value vs. reference
Call by value Call by reference
The function is called by
directly passing value of
variable as argument
The function is called by
directly passing address of
variable as argument
We need to declare a general
variable as function argument
We need to declare a pointer
variable as argument.
Calling function by value does
not changes actual values of
variables
Calling function by reference
changes actual values of
variables
It is a slow way of calling
function as we are calling it by
passing value
It is a fast way of calling
function as we are calling it by
passing address of a variable
http://www.tusharkute.com 26
Example-2:
int swap1(int x, int y)
{
int t;
t = x;
x = y;
y = t;
}
int swap2(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
Pointer to Pointer (char **argv)
http://www.tusharkute.com 27
Passing arguments to main:
int
main(int argc, char **argv)
{
...
}
an array/vector of
char *
Recall when passing an
array, a pointer to the
first element is passed
size of the argv array/vector
Suppose you run the program this way
UNIX% ./program hello 1 2 3
argc == 5 (five strings on the
command line)
http://www.tusharkute.com 28
char **argv
argv[0]
argv[1]
argv[2]
0x1000
0x1008
0x1010
argv[3]
argv[4]
0x1018
0x1020
“./program”
“hello”
“1”
“2”
“3”
These are strings!!
Not integers!
Thank you
This presentation is created using LibreOffice Impress 3.6.2.2

Contenu connexe

Tendances (20)

Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Pointers - DataStructures
Pointers - DataStructuresPointers - DataStructures
Pointers - DataStructures
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
Ponters
PontersPonters
Ponters
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
ppt on pointers
ppt on pointersppt on pointers
ppt on pointers
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
pointers
pointerspointers
pointers
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
C pointer
C pointerC pointer
C pointer
 

Similaire à Module 02 Pointers in C

03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt03-arrays-pointers (1).ppt
03-arrays-pointers (1).pptSyedaNooreen
 
arrays, pointers and operations pointers
arrays, pointers and operations pointersarrays, pointers and operations pointers
arrays, pointers and operations pointersShalabhMishra10
 
03-arrays-pointers.ppt
03-arrays-pointers.ppt03-arrays-pointers.ppt
03-arrays-pointers.pptArifKamal36
 
03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.pptsuriyakalavinoth
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedhozaifafadl
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programmingIcaii Infotech
 

Similaire à Module 02 Pointers in C (20)

See through C
See through CSee through C
See through C
 
03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt
 
arrays, pointers and operations pointers
arrays, pointers and operations pointersarrays, pointers and operations pointers
arrays, pointers and operations pointers
 
03-arrays-pointers.ppt
03-arrays-pointers.ppt03-arrays-pointers.ppt
03-arrays-pointers.ppt
 
03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Pointers
PointersPointers
Pointers
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 

Plus de Tushar B Kute

Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processorTushar B Kute
 
01 Introduction to Android
01 Introduction to Android01 Introduction to Android
01 Introduction to AndroidTushar B Kute
 
Ubuntu OS and it's Flavours
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's FlavoursTushar B Kute
 
Install Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteTushar B Kute
 
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteTushar B Kute
 
Share File easily between computers using sftp
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftpTushar B Kute
 
Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in LinuxTushar B Kute
 
Implementation of FIFO in Linux
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in LinuxTushar B Kute
 
Implementation of Pipe in Linux
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in LinuxTushar B Kute
 
Basic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsTushar B Kute
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxTushar B Kute
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxTushar B Kute
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingTushar B Kute
 
Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Tushar B Kute
 
Open source applications softwares
Open source applications softwaresOpen source applications softwares
Open source applications softwaresTushar B Kute
 
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Tushar B Kute
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteTushar B Kute
 
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTushar B Kute
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 

Plus de Tushar B Kute (20)

Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
 
01 Introduction to Android
01 Introduction to Android01 Introduction to Android
01 Introduction to Android
 
Ubuntu OS and it's Flavours
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's Flavours
 
Install Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. Kute
 
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. Kute
 
Share File easily between computers using sftp
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftp
 
Signal Handling in Linux
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
 
Implementation of FIFO in Linux
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in Linux
 
Implementation of Pipe in Linux
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in Linux
 
Basic Multithreading using Posix Threads
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix Threads
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module Programming
 
Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)
 
Open source applications softwares
Open source applications softwaresOpen source applications softwares
Open source applications softwares
 
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
 
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
 
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrc
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 

Dernier

Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 

Dernier (20)

Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 

Module 02 Pointers in C

  • 1. See through C Module 2 Pointers Tushar B Kute http://tusharkute.com
  • 2. Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including their similarities and differences http://www.tusharkute.com 2
  • 3. http://www.tusharkute.com 3 Arrays in C No bounds checking! Allowed – usually causes no error array[10] may overwrite b Unlike Java, array size in declaration int array[10]; int b; array[0] = 3; array[9] = 4; array[10] = 5; array[-1] = 6; Compare: C: int array[10]; Java: int[] array = new int[10]; All elements of same type – homogenous First element (index 0) Last element (index size - 1)
  • 4. http://www.tusharkute.com 4 Array Representation Homogeneous → Each element same size – s bytes  An array of m data values is a sequence of m×s bytes  Indexing: 0th value at byte s×0, 1st value at byte s×1, … m and s are not part of representation  Unlike in some other languages  s known by compiler – usually irrelevant to programmer  m often known by compiler – if not, must be saved by programmer a[0] a[1] a[2] 0x1000 0x1004 0x1008 int a[3];
  • 5. http://www.tusharkute.com 5 Array Representation char c1; int a[3]; char c2; int i; c1 a[0] a[1] a[2] i 0x1000 0x1004 0x1008 0x100C 0x1014 c20x1010 Could be optimized by making these adjacent, and reducing padding (by default, not) Array aligned by size of elements
  • 6. http://www.tusharkute.com 6 Array Sizes What is sizeof(array[3])? sizeof(array)? int array[10]; 4 40 returns the size of an object in bytes
  • 7. http://www.tusharkute.com 7 Multi-Dimensional Arrays int matrix[2][3]; matrix[1][0] = 17; matrix[0][0] matrix[0][1] matrix[0][2] 0x1000 0x1004 0x1008 matrix[1][0] matrix[1][1] matrix[1][2] 0x100C 0x1010 0x1014 Recall: no bounds checking What happens when you write: matrix[0][3] = 42; “Row Major” Organization
  • 8. http://www.tusharkute.com 8 Sample Program #include<stdio.h> int main() { int arr[10], c; printf(“Enter 10 elements: “); for(c=0;c<10;c++) scanf(“%d”,&arr[c]); printf(“Array elements are: “); for(c=0;c<10;c++) printf(“n%d”,arr[c]); }
  • 9. http://www.tusharkute.com 9 Exercise Programs Program-1  Write a program to input 10 elements from user and find addition of all the numbers. Program-2  Write a program to input 5 numbers from keyboard and find greatest among all the elements. Program-3  Write a program input 10 array elements and separate odd and even numbers from the array.
  • 10. http://www.tusharkute.com 10 Memory Addresses Storage cells are typically viewed as being byte-sized  Usually the smallest addressable unit of memory • Few machines can directly address bits individually  Such addresses are sometimes called byte-addresses Memory is often accessed as words  Usually a word is the largest unit of memory access by a single machine instruction • CLEAR’s word size is 8 bytes (= sizeof(long))  A word-address is simply the byte-address of the word’s first byte
  • 12. http://www.tusharkute.com 12 Pointers Special case of bounded-size natural numbers  Maximum memory limited by processor word-size  232 bytes = 4GB, 264 bytes = 16 exabytes A pointer is just another kind of value  A basic type in C int *ptr; The variable “ptr” is a pointer to an “int”.
  • 13. http://www.tusharkute.com 13 Pointer Operations in C Creation & variable Returns variable’s memory address Dereference * pointer Returns contents stored at address Indirect assignment * pointer = val Stores value at address Of course, still have... Assignment pointer = ptr Stores pointer in another variable
  • 14. http://www.tusharkute.com 14 Using Pointers int i1; int i2; int *ptr1; int *ptr2; i1 = 1; i2 = 2; ptr1 = &i1; ptr2 = ptr1; *ptr1 = 3; i2 = *ptr2; i1: i2: ptr1: 0x1000 0x1004 0x1008 … ptr2: … 0x100C 0x1010 0x1014 1 2 0x1000 0x1000 3 3
  • 15. http://www.tusharkute.com 15 Using Pointers (cont.) Type check warning: int_ptr2 is not an int int1 becomes 8 int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; *int_ptr1 = int_ptr2; *int_ptr1 = int2; What happens?
  • 16. http://www.tusharkute.com 16 Using Pointers (cont.) Type check warning: *int_ptr2 is not an int * Changes int_ptr1 – doesn’t change int1 int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; int_ptr1 = *int_ptr2; int_ptr1 = int_ptr2; What happens?
  • 17. http://www.tusharkute.com 17 Pointer Arithmetic pointer + number pointer – number E.g., pointer + 1 adds 1 something to a pointer char *p; char a; char b; p = &a; p += 1; int *p; int a; int b; p = &a; p += 1;In each, p now points to b (Assuming compiler doesn’t reorder variables in memory) Adds 1*sizeof(char) to the memory address Adds 1*sizeof(int) to the memory address Pointer arithmetic should be used cautiously
  • 18. http://www.tusharkute.com 18 The Simplest Pointer in C Special constant pointer NULL  Points to no data  Dereferencing illegal – causes segmentation fault  To define, include <stdlib.h> or <stdio.h>
  • 19. http://www.tusharkute.com 19 Generic Pointers void *: a “pointer to anything” Lose all information about what type of thing is pointed to  Reduces effectiveness of compiler’s type-checking  Can’t use pointer arithmetic void *p; int i; char c; p = &i; p = &c; putchar(*(char *)p); type cast: tells the compiler to “change” an object’s type (for type checking purposes – does not modify the object in any way) Dangerous! Sometimes necessary…
  • 20. http://www.tusharkute.com 20 Pass-by-Reference void set_x_and_y(int *x, int *y) { *x = 1001; *y = 1002; } void f(void) { int a = 1; int b = 2; set_x_and_y(&a,&b); } 1 2 a b x y 1001 1002
  • 21. http://www.tusharkute.com 21 Arrays and Pointers Dirty “secret”: Array ≈ pointer to the initial (0th) array element a[i] ≡ *(a+i) An array is passed to a function as a pointer  The array size is lost! Usually bad style to interchange arrays and pointers  Avoid pointer arithmetic! Really int *array int foo(int array[], unsigned int size) { … array[size - 1] … } int main(void) { int a[10], b[5]; … foo(a, 10)… foo(b, 5) … } Must explicitly pass the size Passing arrays:
  • 22. http://www.tusharkute.com 22 Arrays and Pointers int a[]={4,5,1,2,8,9,3,0,7,6}; int *p, i; p = a; // points first element. //p = &a[0]; printf("nArray elements are: n"); for(i=0;i<10;i++) { printf(" %dn", *p); p++; }
  • 23. http://www.tusharkute.com 23 Passing arrays to functions Arrays can be passed to the functions as parameters. In such cases the arrays and pointers are not differentiated. e.g. int print(int *a, int c) { int i; for(i=0;i<c;i++,a++) printf("%dn",*a); }
  • 24. http://www.tusharkute.com 24 Returning pointers from functions Pointer can be the return type of the function. It is used for returning multiple values from function. e.g. int * increment(int *a, int c) { int i, *p; p = a; for(i=0;i<c;i++,a++) *a = *a + 1; return p; }
  • 25. http://www.tusharkute.com 25 Call by value vs. reference Call by value Call by reference The function is called by directly passing value of variable as argument The function is called by directly passing address of variable as argument We need to declare a general variable as function argument We need to declare a pointer variable as argument. Calling function by value does not changes actual values of variables Calling function by reference changes actual values of variables It is a slow way of calling function as we are calling it by passing value It is a fast way of calling function as we are calling it by passing address of a variable
  • 26. http://www.tusharkute.com 26 Example-2: int swap1(int x, int y) { int t; t = x; x = y; y = t; } int swap2(int *x, int *y) { int t; t = *x; *x = *y; *y = t; }
  • 27. Pointer to Pointer (char **argv) http://www.tusharkute.com 27 Passing arguments to main: int main(int argc, char **argv) { ... } an array/vector of char * Recall when passing an array, a pointer to the first element is passed size of the argv array/vector Suppose you run the program this way UNIX% ./program hello 1 2 3 argc == 5 (five strings on the command line)
  • 29. Thank you This presentation is created using LibreOffice Impress 3.6.2.2