SlideShare uma empresa Scribd logo
1 de 36
POINTERS
INTRODUCTION
• A pointer is a derived data type in C.
• Pointers contain memory addresses as their values.
• Since these memory addresses are the locations in
the computer memory where program instructions
and data are stored, pointers can be used to access
and manipulate data stored in the memory.
POINTERS BENEFITS TO THE
PROGRAMMER
• Pointers are more efficient in handling arrays and data tables.
• Pointers can be used to return multiple values from a function via
function arguments.
• Pointers permit references to functions and thereby facilitating passing of
function as arguments to other functions.
• The use of pointers arrays to character stings results in saving of data
storage space in memory.
• Pointers allow C to support dynamic memory management.
• Pointers provide an efficient tool for manipulating dynamic data
structures such as structures, linked lists, queues, stacks and trees.
• Pointers reduce length and complexity of programs.
• They increase the execution speed and thus reduce the program
execution time.
UNDERSTANDING POINTER
• The computer’s memory is a
sequential collection of storage cells
• Each cell. Commonly known as a byte,
has a number called address
associated with it
• The address are numbers
consecutively, starting from zero
• The last address depends on the
memory size
• A computer system having 64K
memory will have its last address as
65,535
POINTER VARIABLE
• We may access the value 547 by using either the
name X or the address 4000.
• Since memory addresses are simply numbers, they
can be assigned to some variables, that can be
stored in memory, like any other variable.
• Such variables that hold memory addresses are
called pointer variables.
• A pointer variable is, nothing but a variable that
contains an address, which is a location of another
variable in memory.
ACCESSING THE ADDRESS OF A
VARIABLE
• The actual location of a variable in the memory is
system dependent.
• We can determine the address of a variable with the
help of the operator & available in C.
• The operator & immediately preceding a variable
returns the address of the variable associated with it.
p = &quantity
• Would assign the address 5000 to the variable p
CHAIN OF POINTERS
• It is possible to make a pointer to point to another pointer,
thus creating a chain of pointers.
• The pointer variable p2 contains the address of the pointer
variable p1, which points to the location that contains the
desired value. This is known as multiple indirections.
• A variable that is a pointer to a pointer must be declared
using additional indirection operator symbols in front of the
name.
• This declaration tells the compiler that p2 is a pointer to a
pointer of int type.
CHAIN OF POINTERS
• We can access the target value indirectly pointed to by
pointer to a pointer by applying the indirection operator
twice.
main()
{
int x, *p1, **p2;
x = 100;
p1 = &x; /* address of x */
p2 = &p1; /* address of p1 */
printf("%d", **p2);
}
POINTER EXPRESSION
• Like other variables, pointer variables can be used in
expressions.
• If p1 and p2 are properly declared and initialized pointers, the
following statements are valid:
y = *p1 * *p2 same as (*p1) * (*p2)
sum = sum + *p1;
z = 5* - *p2/ *p1; same as (5 * (-(*p2)))/(*p1)
*p2 = *p2 +10;
• Note the blank space between / and *. the following is wrong
z = 5* - *p2 /*p1;
• The symbol /* is considered as the beginning of a comment
POINTER EXPRESSION
• C allows us to add integers to or subtract integers from pointers,
as well as to subtract one pointer from another.
p1 + 4, p2 – 2, p1 - p2 are all allowed
• If p1 and p2 are both pointer to the same array, then p2-p1 gives
the number of elements between p1 and p2.
• We may also use short-hand operators with the pointers.
p1++; -p2; sum += *p2;
• Pointer can also be compared using the relational operators.
p1 > p2, p1 == p2, p1 != p2 are allowed
• We may not use pointers in division or multiplication.
p1/p2 or p1 * p2 or p1 / 3 are not allowed
• Two pointer cannot be added.
p1 + p2 is illegal
EXAMPLE
main()
{
int a, b, *p1, *p2, x, y, z;
a = 12;
b = 4;
p1 = &a;
p2 = &b;
x = *p1 * *p2 -6;
y = 4* - *p2 / *p1 + 10;
printf("Address of a = %dn", p1);
printf("Address of a = %dn", p2);
printf("n");
printf("a = %d, b = %dn", a, b);
printf("x = %d, y = %dn", x, y);
*p2 = *p2 + 3;
*p1 = *p2 - 5;
z = *p1 * *p2 - 6;
printf("na = %d, b = %d,", a, b);
printf(" z = %dn",z);
}
OUTPUT:
Address of a = 4020
Address of b = 4016
a = 12, b = 4
x = 42, y = 9
a = 2, b = 7, z = 8
Pointer Increments and Scale Factor
• Arithmetic operations can be performed on pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
• The pointers can be incremented like
p1 = p1 + 2;
p1 = p1 + 1;
• Expression like
p1++;
• Will cause the pointer p1 to point to the next value of its type
• When a pointer is incremented, its value is increased by the
‘length’ of the data type that it points to
• This length called the scale factor
Pointers and Arrays
• When an array is declared, the compiler allocates a base address
and sufficient amount of storage to contain all the elements of
the array in contiguous memory locations
• The base address is the location of the first elements (index 0) of
the array
• The compiler also defines the array name as the constant pointer
to the first element
int x[5] = {1, 2, 3, 4, 5};
• Base address of x is 1000
• Each integer requires two bytes
• The name x is defined as a constant pointer pointing to the first
element, x[0]
• The value of x is 1000, the location where x[0] is stored
x = &x[0] = 1000
• Declare p as an integer pointer, then we can make the pointer p
to point to the array x
p = x;
Pointers and Arrays
• This is equivalent to
p = &x[0];
• We can access every value of x using p++ to move from one
element to another
• The relationship between p and x is
p = &x[0] (=1000)
p+1 = &x[1] (=1002)
p+2 = &x[2] (=1004)
p+3 = &x[3] (=1006)
P+4 = &x[4] (=1008)
• The address of an element is calculated using its index and the
scale factor of the data type
Address of x[3] = base address + (3 x scale factor of int)
= 1000 + (3 x 2) = 1006
• When handling arrays, instead of using array indexing, we can
use pointers to access array elements.
• The pointer accessing method is much faster than array
indexing.
EXAMPLE
main()
{
int *p, sum, i;
int x[5] = {5,9,6,2,7};
i = 0; p = x;
printf("Element Value Addressnn");
while(i<5)
{
printf(" x[%d] %d %dn",i, *p, p);
sum = sum + *p;
i++; p++;
}
printf("n Sum = %dn", sum);
printf("n &x[0] = %dn", &x[0]);
printf("n p = %dn", p);
}
OUTPUT:
Element Value Address
x[0] 5 166
x[1] 9 168
x[2] 6 170
x[3] 3 172
x[4] 7 174
Sum = 55
&x[0] = 166
p = 176
POINTERS TO 2D ARRAYS
• Pointers can be used to manipulate two-dimensional arrays as
well.
• In a one-dimensional array x, the expression
*(x+i) or *(p+i)
• Represents the elements x[i].
• An element in a two-dimensional array can be represented by
the pointer expression as:
*(*(a+i)+j) or *(*(p+i)+j)
POINTERS AND CHARACTER STRINGS
• The strings are treated as character arrays and therefore they are
declared and initialized as
char str[5] = “good”;
• The compiler automatically inserts the null character ‘0’ at the
end of the string.
• Alternate method to create stings is by using pointer variables of
type char.
char *str = “good”;
• This creates a string and then stores its address in the pointer
variable str.
• The pointer str now points to the first character of the string
“good” as:
• We can use the run-time assignment for giving values to a
string pointer.
char * string1;
string1 = “good”;
• The above assignment is not a string copy, because the
variable string1 is a pointer, not a string.
• We can print the content of the string string1 using either
printf or puts functions as
printf(“%s”, string1);
puts(string1);
• Although string1 is a pointer to the string, it is also the name of
the string. Therefore we do not need to use the indirection
operator * here
POINTERS AND CHARACTER STRINGS
EXAMPLE
main()
{
char *name;
int length;
char *cptr = name;
name = DELHI;
printf("%sn“,name);
while(*cptr != '0')
{
pritf("%c is stored at address %dn", *cptr, cptr);
cptr++;
}
length = cptr - name;
printf("nLength of the string = %dn", length);
}
OUTPUT:
DELHI
D is stored at address 54
E is stored at address 55
L is stored at address 56
H is stored at address 57
I is stored at address 58
Length of the string = 5
POINTER AS FUNCTION ARGUMENTS
• When an array is passed to a function as an argument, only the
address of the first element of the array is passed, but no the
actual values of the array elements.
• If x is an array, when we call sort(x), the address of x[0] is passed
to the function sort.
• The function used this address for manipulating the array
elements.
• We can also pass the address of a variable as an argument to a
function.
• When we pass addresses to function, the parameters receiving
the addresses should be pointers.
• The process of calling a function using pointers to pass the
addresses of variables is known as ‘call by reference’.
• The function called by ‘reference’ can change the value of the
variable used in the call.
EXAMPLE
main()
{
int x;
x = 20;
change(&x);
printf("%dn",x);
}
change(int *P)
{
*P = *P + 10;
}
OUTPUT:
30
Pointers with Functions (example)
void swap ( int *, int * ) ;
main ( )
{
int a = 5, b = 6;
printf(“Before Swapping : a=%d b=%dn",a,b) ;
swap (&a, &b) ;
printf(“After swapping : a=%d b=%dn",a,b) ;
}
void swap( int *a, int *b )
{
int temp;
temp= *a; *a= *b; *b = temp ;
}
Results:
Before Swapping : a=5 b=6
After Swapping : a=6 b=5
FUNTION RETURNING POINTERS
• Function can also return a pointer to the calling function
int *larger (int *, int *);
main() {
int a = 10, b = 20;
int *p;
p = larger(&a, &b);
printf("%d", *p);
}
int *larger(int *x, int *y)
{
if(*x>*y)
return(x);
else
return(y);
}
THE END

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
Structure in C
Structure in CStructure in C
Structure in C
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
C Pointers
C PointersC Pointers
C Pointers
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
File in C language
File in C languageFile in C language
File in C language
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Strings in C
Strings in CStrings in C
Strings in C
 
POINTERS IN C
POINTERS IN CPOINTERS IN C
POINTERS IN C
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Type conversion
Type conversionType conversion
Type conversion
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Function in C
Function in CFunction in C
Function in C
 

Destaque

C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 

Destaque (20)

Deep C Programming
Deep C ProgrammingDeep C Programming
Deep C Programming
 
C pointer
C pointerC pointer
C pointer
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Difference between structure and union
Difference between structure and unionDifference between structure and union
Difference between structure and union
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Types of storage class specifiers in c programming
Types of storage class specifiers in c programmingTypes of storage class specifiers in c programming
Types of storage class specifiers in c programming
 
Pointers
PointersPointers
Pointers
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
a project report on MPPT algorithm for PV panel
a project report on MPPT algorithm for PV panela project report on MPPT algorithm for PV panel
a project report on MPPT algorithm for PV panel
 
MEP- Building services
MEP- Building servicesMEP- Building services
MEP- Building services
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015BE Aerospace Syllabus of MIT, Anna University R2015
BE Aerospace Syllabus of MIT, Anna University R2015
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
Commercial Design Considerations & Solectria Solutions
Commercial Design Considerations & Solectria Solutions Commercial Design Considerations & Solectria Solutions
Commercial Design Considerations & Solectria Solutions
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
C pointers
C pointersC pointers
C pointers
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 

Semelhante a Pointers C programming

pointers of the programming in c most efficient.pptx
pointers of the programming in c most efficient.pptxpointers of the programming in c most efficient.pptx
pointers of the programming in c most efficient.pptx
AmitRout25
 

Semelhante a Pointers C programming (20)

PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Pointers
PointersPointers
Pointers
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Chap 11(pointers)
Chap 11(pointers)Chap 11(pointers)
Chap 11(pointers)
 
Pointers
PointersPointers
Pointers
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
 
pointers of the programming in c most efficient.pptx
pointers of the programming in c most efficient.pptxpointers of the programming in c most efficient.pptx
pointers of the programming in c most efficient.pptx
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
Session 5
Session 5Session 5
Session 5
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
SPC Unit 3
SPC Unit 3SPC Unit 3
SPC Unit 3
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
c-arrays-pointers.ppt
c-arrays-pointers.pptc-arrays-pointers.ppt
c-arrays-pointers.ppt
 
c-arrays-pointer basics xxxx yyyy zzzzzzz
c-arrays-pointer basics xxxx yyyy zzzzzzzc-arrays-pointer basics xxxx yyyy zzzzzzz
c-arrays-pointer basics xxxx yyyy zzzzzzz
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 

Pointers C programming

  • 2. INTRODUCTION • A pointer is a derived data type in C. • Pointers contain memory addresses as their values. • Since these memory addresses are the locations in the computer memory where program instructions and data are stored, pointers can be used to access and manipulate data stored in the memory.
  • 3. POINTERS BENEFITS TO THE PROGRAMMER • Pointers are more efficient in handling arrays and data tables. • Pointers can be used to return multiple values from a function via function arguments. • Pointers permit references to functions and thereby facilitating passing of function as arguments to other functions. • The use of pointers arrays to character stings results in saving of data storage space in memory. • Pointers allow C to support dynamic memory management. • Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees. • Pointers reduce length and complexity of programs. • They increase the execution speed and thus reduce the program execution time.
  • 4. UNDERSTANDING POINTER • The computer’s memory is a sequential collection of storage cells • Each cell. Commonly known as a byte, has a number called address associated with it • The address are numbers consecutively, starting from zero • The last address depends on the memory size • A computer system having 64K memory will have its last address as 65,535
  • 5.
  • 6. POINTER VARIABLE • We may access the value 547 by using either the name X or the address 4000. • Since memory addresses are simply numbers, they can be assigned to some variables, that can be stored in memory, like any other variable. • Such variables that hold memory addresses are called pointer variables. • A pointer variable is, nothing but a variable that contains an address, which is a location of another variable in memory.
  • 7. ACCESSING THE ADDRESS OF A VARIABLE • The actual location of a variable in the memory is system dependent. • We can determine the address of a variable with the help of the operator & available in C. • The operator & immediately preceding a variable returns the address of the variable associated with it. p = &quantity • Would assign the address 5000 to the variable p
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19. CHAIN OF POINTERS • It is possible to make a pointer to point to another pointer, thus creating a chain of pointers. • The pointer variable p2 contains the address of the pointer variable p1, which points to the location that contains the desired value. This is known as multiple indirections. • A variable that is a pointer to a pointer must be declared using additional indirection operator symbols in front of the name. • This declaration tells the compiler that p2 is a pointer to a pointer of int type.
  • 20. CHAIN OF POINTERS • We can access the target value indirectly pointed to by pointer to a pointer by applying the indirection operator twice. main() { int x, *p1, **p2; x = 100; p1 = &x; /* address of x */ p2 = &p1; /* address of p1 */ printf("%d", **p2); }
  • 21. POINTER EXPRESSION • Like other variables, pointer variables can be used in expressions. • If p1 and p2 are properly declared and initialized pointers, the following statements are valid: y = *p1 * *p2 same as (*p1) * (*p2) sum = sum + *p1; z = 5* - *p2/ *p1; same as (5 * (-(*p2)))/(*p1) *p2 = *p2 +10; • Note the blank space between / and *. the following is wrong z = 5* - *p2 /*p1; • The symbol /* is considered as the beginning of a comment
  • 22. POINTER EXPRESSION • C allows us to add integers to or subtract integers from pointers, as well as to subtract one pointer from another. p1 + 4, p2 – 2, p1 - p2 are all allowed • If p1 and p2 are both pointer to the same array, then p2-p1 gives the number of elements between p1 and p2. • We may also use short-hand operators with the pointers. p1++; -p2; sum += *p2; • Pointer can also be compared using the relational operators. p1 > p2, p1 == p2, p1 != p2 are allowed • We may not use pointers in division or multiplication. p1/p2 or p1 * p2 or p1 / 3 are not allowed • Two pointer cannot be added. p1 + p2 is illegal
  • 23. EXAMPLE main() { int a, b, *p1, *p2, x, y, z; a = 12; b = 4; p1 = &a; p2 = &b; x = *p1 * *p2 -6; y = 4* - *p2 / *p1 + 10; printf("Address of a = %dn", p1); printf("Address of a = %dn", p2); printf("n"); printf("a = %d, b = %dn", a, b); printf("x = %d, y = %dn", x, y); *p2 = *p2 + 3; *p1 = *p2 - 5; z = *p1 * *p2 - 6; printf("na = %d, b = %d,", a, b); printf(" z = %dn",z); } OUTPUT: Address of a = 4020 Address of b = 4016 a = 12, b = 4 x = 42, y = 9 a = 2, b = 7, z = 8
  • 24. Pointer Increments and Scale Factor • Arithmetic operations can be performed on pointers – Increment/decrement pointer (++ or --) – Add an integer to a pointer( + or += , - or -=) – Pointers may be subtracted from each other • The pointers can be incremented like p1 = p1 + 2; p1 = p1 + 1; • Expression like p1++; • Will cause the pointer p1 to point to the next value of its type • When a pointer is incremented, its value is increased by the ‘length’ of the data type that it points to • This length called the scale factor
  • 25. Pointers and Arrays • When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations • The base address is the location of the first elements (index 0) of the array • The compiler also defines the array name as the constant pointer to the first element int x[5] = {1, 2, 3, 4, 5}; • Base address of x is 1000 • Each integer requires two bytes • The name x is defined as a constant pointer pointing to the first element, x[0] • The value of x is 1000, the location where x[0] is stored x = &x[0] = 1000 • Declare p as an integer pointer, then we can make the pointer p to point to the array x p = x;
  • 26. Pointers and Arrays • This is equivalent to p = &x[0]; • We can access every value of x using p++ to move from one element to another • The relationship between p and x is p = &x[0] (=1000) p+1 = &x[1] (=1002) p+2 = &x[2] (=1004) p+3 = &x[3] (=1006) P+4 = &x[4] (=1008) • The address of an element is calculated using its index and the scale factor of the data type Address of x[3] = base address + (3 x scale factor of int) = 1000 + (3 x 2) = 1006 • When handling arrays, instead of using array indexing, we can use pointers to access array elements. • The pointer accessing method is much faster than array indexing.
  • 27. EXAMPLE main() { int *p, sum, i; int x[5] = {5,9,6,2,7}; i = 0; p = x; printf("Element Value Addressnn"); while(i<5) { printf(" x[%d] %d %dn",i, *p, p); sum = sum + *p; i++; p++; } printf("n Sum = %dn", sum); printf("n &x[0] = %dn", &x[0]); printf("n p = %dn", p); } OUTPUT: Element Value Address x[0] 5 166 x[1] 9 168 x[2] 6 170 x[3] 3 172 x[4] 7 174 Sum = 55 &x[0] = 166 p = 176
  • 28. POINTERS TO 2D ARRAYS • Pointers can be used to manipulate two-dimensional arrays as well. • In a one-dimensional array x, the expression *(x+i) or *(p+i) • Represents the elements x[i]. • An element in a two-dimensional array can be represented by the pointer expression as: *(*(a+i)+j) or *(*(p+i)+j)
  • 29. POINTERS AND CHARACTER STRINGS • The strings are treated as character arrays and therefore they are declared and initialized as char str[5] = “good”; • The compiler automatically inserts the null character ‘0’ at the end of the string. • Alternate method to create stings is by using pointer variables of type char. char *str = “good”; • This creates a string and then stores its address in the pointer variable str. • The pointer str now points to the first character of the string “good” as:
  • 30. • We can use the run-time assignment for giving values to a string pointer. char * string1; string1 = “good”; • The above assignment is not a string copy, because the variable string1 is a pointer, not a string. • We can print the content of the string string1 using either printf or puts functions as printf(“%s”, string1); puts(string1); • Although string1 is a pointer to the string, it is also the name of the string. Therefore we do not need to use the indirection operator * here POINTERS AND CHARACTER STRINGS
  • 31. EXAMPLE main() { char *name; int length; char *cptr = name; name = DELHI; printf("%sn“,name); while(*cptr != '0') { pritf("%c is stored at address %dn", *cptr, cptr); cptr++; } length = cptr - name; printf("nLength of the string = %dn", length); } OUTPUT: DELHI D is stored at address 54 E is stored at address 55 L is stored at address 56 H is stored at address 57 I is stored at address 58 Length of the string = 5
  • 32. POINTER AS FUNCTION ARGUMENTS • When an array is passed to a function as an argument, only the address of the first element of the array is passed, but no the actual values of the array elements. • If x is an array, when we call sort(x), the address of x[0] is passed to the function sort. • The function used this address for manipulating the array elements. • We can also pass the address of a variable as an argument to a function. • When we pass addresses to function, the parameters receiving the addresses should be pointers. • The process of calling a function using pointers to pass the addresses of variables is known as ‘call by reference’. • The function called by ‘reference’ can change the value of the variable used in the call.
  • 33. EXAMPLE main() { int x; x = 20; change(&x); printf("%dn",x); } change(int *P) { *P = *P + 10; } OUTPUT: 30
  • 34. Pointers with Functions (example) void swap ( int *, int * ) ; main ( ) { int a = 5, b = 6; printf(“Before Swapping : a=%d b=%dn",a,b) ; swap (&a, &b) ; printf(“After swapping : a=%d b=%dn",a,b) ; } void swap( int *a, int *b ) { int temp; temp= *a; *a= *b; *b = temp ; } Results: Before Swapping : a=5 b=6 After Swapping : a=6 b=5
  • 35. FUNTION RETURNING POINTERS • Function can also return a pointer to the calling function int *larger (int *, int *); main() { int a = 10, b = 20; int *p; p = larger(&a, &b); printf("%d", *p); } int *larger(int *x, int *y) { if(*x>*y) return(x); else return(y); }

Notas do Editor

  1. Instructor/Narrator: Here is a modified swap program. Notice the swap function now requires pointer variables as input (both in the function and function prototype), and that all operations are done by dereferencing the pointers within the swap function to get the values and move them around with the aid of the local “temp” variable. In the main() function the addresses of the a and b variable are passed to the swap() function (given by &amp;a and &amp;b). The results are now what would be expected of a swap function.