SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Pointers
Pointers
• A pointer is a variable that points to or
references a memory location in which data
is stored.
• Each memory cell in the computer has an
address that can be used to access that
location so a pointer variable points to a
memory location we can access and change
the contents of this memory location via the
pointer.

2
Pointers
• Pointer declaration:
• A pointer is a variable that contains the memory location
of another variable.
• The syntax is as shown below.
• Start by specifying the type of data stored in the location
identified by the pointer.
• The asterisk tells the compiler that you are creating a
pointer variable.
• Finally you give the name of the variable.
• type * variable name
• Example:
• int *ptr;
• float *string;
3
Pointers
• Address operator:
• Once we declare a pointer variable we must
point it to something we can do this by assigning
to the pointer the address of the variable you
want to point as in the following example:
• ptr=#
• This places the address where num is stores into
the variable ptr.
• If num is stored in memory 21260 address then
the variable ptr has the value 21260.
4
Pointers
•
•
•
•
•
•
•
•
•
•
•

/* A program to illustrate pointer declaration*/
#include<stdio.h>
main()
{
int *ptr;
int sum;
sum=45;
ptr=&sum;
printf("n Sum is %d",sum);
printf("n The sum pointer is %u", ptr);
}
5
Pointers
int i1;
int i2;
int *ptr1;
int *ptr2;

0x1014

…

0x1010

ptr2:

i1 = 1;
i2 = 2;

0x100C

…

0x1008

ptr1:

ptr1 = &i1;
ptr2 = ptr1;

0x1004

i2:

2
3

0x1000

i1:

3
1

0x1000

0x1000

*ptr1 = 3;
i2 = *ptr2;

Cox & Ng

Arrays and Pointers

6
Pointers
• Pointer expressions & pointer arithmetic:
• Like other variables pointer variables can be used in expressions.
• For example if p1 and p2 are properly declared and initialized
pointers, then the following statements are valid.
• y=*p1**p2;
• sum=sum+*p1;
• z= 5* - *p2/p1;
• *p2= *p2 + 10;
• C allows to add integers to or subtract integers from pointers as
well as to subtract one pointer from the other.
• We can also use short hand operators with the pointers
• p1+=; sum+=*p2; etc.,
• we can also compare pointers by using relational operators the
expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.

7
Pointers
•
•
•
•
•
•
•
•
•
•
•
•
•
•

/*Program to illustrate the pointer expression and pointer arithmetic*/
#include<stdio.h>
main()
{
int *ptr1,*ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2- 6;
y=6*- *ptr1/ *ptr2 +30;
printf("na=%d, b=%d",a,b);
printf("nx=%d,y=%d",x,y);
}

8
Pointers
•
•
•
•
•

Pointers and function:
1. Call by reference
2. Call by value.
Call by Reference:
When we pass address to a function the
parameters receiving the address should be
pointers. The process of calling a function by
using pointers to pass the address of the
variable is known as call by reference. The
function which is called by reference can change
the values of the variable used in the call.
9
Pointers
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

/* example of call by reference*/
#include<stdio.h>
void main()
{
void fncn(int *,int *);
int a=20,b=30;
printf("n Value of a and b before function call =%d %d",a,b);
fncn(&a,&b);
printf("n Value of a and b after function call =%d %d",a,b);
}
void fncn(int *p,int *q)
{
*p=100;
*q=200;
}

10
Pointers
• Pointer to arrays:
• An array is actually very much like pointer.
• We can declare the arrays first element as a[0]
or as int *a because a[0] is an address and *a is
also an address the form of declaration is
equivalent.
• The difference is pointer is a variable and can
appear on the left of the assignment operator
that is lvalue.
• The array name is constant and cannot appear
as the left side of assignment operator.
11
Pointers
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

/* A program to display the contents of array using pointer*/
#include<stdio.h>
main()
{
int a[100];
int i,j,n,*ptr;
printf("nEnter the elements of the arrayn");
scanf("%d",&n);
printf("Enter the array elements");
for(i=0;i< n;i++)
{
scanf("%d",&a[i]);
}
printf("Array element are");
for(ptr=a;ptr<(a+n);ptr++)
{
printf("nValue of stored at address %u",ptr);
}
}

12
Pointers
•
•
•
•
•
•
•
•
•
•
•

Multi-Dimensional Arrays
int multi[ROWS][COLS];
we can access individual elements of the array multi using either:
multi[row][col]
or
*(*(multi + row) + col)
To understand more fully what is going on, let us replace
*(multi + row)
with X as in:
*(X + col)
Now, from this we see that X is like a pointer since the expression is
de-referenced and we know that col is an integer. The arithmetic being used here
is of a special kind called "pointer arithmetic". That means that, since we are
talking about an integer array, the address pointed to by (i.e. value of) X + col + 1
must be greater than the address X + col by and amount equal to sizeof(int).

13
Pointers
• Since we know the memory layout for 2 dimensional
arrays, we can determine that in the expression multi +
row as used above, multi + row + 1 must increase by value
an amount equal to that needed to "point to" the next
row, which in this case would be an amount equal to COLS
* sizeof(int).
• That says that if the expression *(*(multi + row) + col) is to
be evaluated correctly at run time, the compiler must
generate code which takes into consideration the value of
COLS, i.e. the 2nd dimension. Because of the equivalence
of the two forms of expression, this is true whether we
are using the pointer expression as here or the array
expression multi[row][col].
14
Pointers
• Thus, to evaluate either expression, a total of 5 values must be
known:
• The address of the first element of the array, which is returned by
the expression multi, i.e., the name of the array.
• The size of the type of the elements of the array, in this case
sizeof(int).
• The 2nd dimension of the array
• The specific index value for the first dimension, row in this case.
• The specific index value for the second dimension, col in this case.
• Given all of that, consider the problem of designing a function to
manipulate the element values of a previously declared array. For
example, one which would set all the elements of the array multi
to the value 1.

15
Pointers
•

More on Strings

•

Well, we have progressed quite a way in a short time! Let's back up a little and look at what was done in Chapter
3 on copying of strings but in a different light. Consider the following function:
char *my_strcpy(char dest[], char source[])
{
int i = 0;
while (source[i] != '')
{
dest[i] = source[i];
i++;
}
dest[i] = '';
return dest;
}

•
•
•
•
•
•
•
•
•
•
•
•

Recall that strings are arrays of characters. Here we have chosen to use array notation instead of pointer
notation to do the actual copying. The results are the same, i.e. the string gets copied using this notation just as
accurately as it did before. This raises some interesting points which we will discuss.

•

Since parameters are passed by value, in both the passing of a character pointer or the name of the array as
above, what actually gets passed is the address of the first element of each array. Thus, the numerical value of
the parameter passed is the same whether we use a character pointer or an array name as a parameter. This
would tend to imply that somehow source[i] is the same as *(p+i).

16
Pointers
•

Pointers to Functions

•

Up to this point we have been discussing pointers to data objects. C also permits
the declaration of pointers to functions. Pointers to functions have a variety of
uses and some of them will be discussed here.

•

Consider the following real problem. You want to write a function that is capable
of sorting virtually any collection of data that can be stored in an array. This
might be an array of strings, or integers, or floats, or even structures. The sorting
algorithm can be the same for all. For example, it could be a simple bubble sort
algorithm, or the more complex shell or quick sort algorithm. We'll use a simple
bubble sort for demonstration purposes.

•

Sedgewick [1] has described the bubble sort using C code by setting up a function
which when passed a pointer to the array would sort it. If we call that function
bubble(), a sort program is described by bubble_1.c, which follow

17
Pointers
•

/* Program bubble_3.c from PTRTUT10.HTM 6/13/97 */

•

#include <stdio.h>

•

int arr[10] = { 3,6,1,2,3,8,4,1,7,2};

•
•

void bubble(int *p, int N);
int compare(int *m, int *n);

•
•
•
•
•

int main(void)
{
int i;
putchar('
');

•
•
•
•
•
•
•

for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
bubble(arr,10);
putchar('

');

•
•
•
•
•
•

}

•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

void bubble(int *p, int N)
{
int i, j, t;
for (i = N-1; i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (compare(&p[j-1], &p[j]))
{
t = p[j-1];
p[j-1] = p[j];
p[j] = t;
}
}
}
}

for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;

18
Pointers
•
•
•
•
•
•
•
•
•
•
•

#include<stdio.h>
void main(){
int i = 3;
int *j;
int **k;
j=&i;
k=&j;
printf(" %d ",**k);
}
Explanation:
Memory representation
19
Pointers
•

Here 6024, 8085, 9091 is any arbitrary address, it may be different.

•

Value of k is content of k in memory which is 8085

•

Value of *k means content of memory location which address k keeps.

•
•
•
•
•
•
•
•
•
•

k keeps address 8085 .
Content of at memory location 8085 is 6024
In the same way **k will equal to 3.
Short cut way to calculate:
Rule: * and & always cancel to each other
i.e. *&a = a
So *k = *(&j) since k = &j
*&j = j = 6024
And
**k = **(&j) = *(*&j) = *j = *(&i) = *&i = i = 3

20
Pointers

21

Weitere ähnliche Inhalte

Was ist angesagt?

C programming - Pointer and DMA
C programming - Pointer and DMAC programming - Pointer and DMA
C programming - Pointer and DMAAchyut Devkota
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanMohammadSalman129
 
C Pointers
C PointersC Pointers
C Pointersomukhtar
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c programRumman Ansari
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingAbdullah Jan
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in CUri Dekel
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - PointersWingston
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in CShivanshuVerma11
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1tanmaymodi4
 

Was ist angesagt? (20)

Pointers_c
Pointers_cPointers_c
Pointers_c
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
C programming - Pointer and DMA
C programming - Pointer and DMAC programming - Pointer and DMA
C programming - Pointer and DMA
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
C Pointers
C PointersC Pointers
C Pointers
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
pointers
pointerspointers
pointers
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ Programming
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in C
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 

Andere mochten auch

Lec 13. Introduction to Pointers
Lec 13. Introduction to PointersLec 13. Introduction to Pointers
Lec 13. Introduction to PointersRushdi Shams
 
Lec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement OperatorsLec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement OperatorsRushdi Shams
 

Andere mochten auch (10)

CPP08 - Pointers
CPP08 - PointersCPP08 - Pointers
CPP08 - Pointers
 
Pointers
PointersPointers
Pointers
 
Lec 13. Introduction to Pointers
Lec 13. Introduction to PointersLec 13. Introduction to Pointers
Lec 13. Introduction to Pointers
 
Structure
StructureStructure
Structure
 
Lec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement OperatorsLec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement Operators
 
Lec 18. Recursion
Lec 18. RecursionLec 18. Recursion
Lec 18. Recursion
 
Recursion prog
Recursion progRecursion prog
Recursion prog
 
Recursion prog (1)
Recursion prog (1)Recursion prog (1)
Recursion prog (1)
 
Type conversion
Type conversionType conversion
Type conversion
 
Computer Programming- Lecture 11
Computer Programming- Lecture 11Computer Programming- Lecture 11
Computer Programming- Lecture 11
 

Ähnlich wie Pointers

Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxRamakrishna Reddy Bijjam
 
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.pptxsangeeta borde
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptxsajinis3
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C languageMehwish Mehmood
 
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.pdfsudhakargeruganti
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptchintuyadav19
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 

Ähnlich wie Pointers (20)

l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
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
 
20.C++Pointer.pptx
20.C++Pointer.pptx20.C++Pointer.pptx
20.C++Pointer.pptx
 
pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C language
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
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
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
Pointers.pdf
Pointers.pdfPointers.pdf
Pointers.pdf
 

Mehr von Frijo Francis

Mehr von Frijo Francis (8)

Data type
Data typeData type
Data type
 
C programming language
C programming languageC programming language
C programming language
 
Break and continue
Break and continueBreak and continue
Break and continue
 
6 enumerated, typedef
6 enumerated, typedef6 enumerated, typedef
6 enumerated, typedef
 
5bit field
5bit field5bit field
5bit field
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
Union
UnionUnion
Union
 
1file handling
1file handling1file handling
1file handling
 

Kürzlich hochgeladen

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
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...christianmathematics
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
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.pdfAdmir Softic
 

Kürzlich hochgeladen (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
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...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.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
 

Pointers

  • 2. Pointers • A pointer is a variable that points to or references a memory location in which data is stored. • Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. 2
  • 3. Pointers • Pointer declaration: • A pointer is a variable that contains the memory location of another variable. • The syntax is as shown below. • Start by specifying the type of data stored in the location identified by the pointer. • The asterisk tells the compiler that you are creating a pointer variable. • Finally you give the name of the variable. • type * variable name • Example: • int *ptr; • float *string; 3
  • 4. Pointers • Address operator: • Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: • ptr=&num; • This places the address where num is stores into the variable ptr. • If num is stored in memory 21260 address then the variable ptr has the value 21260. 4
  • 5. Pointers • • • • • • • • • • • /* A program to illustrate pointer declaration*/ #include<stdio.h> main() { int *ptr; int sum; sum=45; ptr=&sum; printf("n Sum is %d",sum); printf("n The sum pointer is %u", ptr); } 5
  • 6. Pointers int i1; int i2; int *ptr1; int *ptr2; 0x1014 … 0x1010 ptr2: i1 = 1; i2 = 2; 0x100C … 0x1008 ptr1: ptr1 = &i1; ptr2 = ptr1; 0x1004 i2: 2 3 0x1000 i1: 3 1 0x1000 0x1000 *ptr1 = 3; i2 = *ptr2; Cox & Ng Arrays and Pointers 6
  • 7. Pointers • Pointer expressions & pointer arithmetic: • Like other variables pointer variables can be used in expressions. • For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid. • y=*p1**p2; • sum=sum+*p1; • z= 5* - *p2/p1; • *p2= *p2 + 10; • C allows to add integers to or subtract integers from pointers as well as to subtract one pointer from the other. • We can also use short hand operators with the pointers • p1+=; sum+=*p2; etc., • we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed. 7
  • 8. Pointers • • • • • • • • • • • • • • /*Program to illustrate the pointer expression and pointer arithmetic*/ #include<stdio.h> main() { int *ptr1,*ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2- 6; y=6*- *ptr1/ *ptr2 +30; printf("na=%d, b=%d",a,b); printf("nx=%d,y=%d",x,y); } 8
  • 9. Pointers • • • • • Pointers and function: 1. Call by reference 2. Call by value. Call by Reference: When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call. 9
  • 10. Pointers • • • • • • • • • • • • • • • /* example of call by reference*/ #include<stdio.h> void main() { void fncn(int *,int *); int a=20,b=30; printf("n Value of a and b before function call =%d %d",a,b); fncn(&a,&b); printf("n Value of a and b after function call =%d %d",a,b); } void fncn(int *p,int *q) { *p=100; *q=200; } 10
  • 11. Pointers • Pointer to arrays: • An array is actually very much like pointer. • We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. • The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. • The array name is constant and cannot appear as the left side of assignment operator. 11
  • 12. Pointers • • • • • • • • • • • • • • • • • • • /* A program to display the contents of array using pointer*/ #include<stdio.h> main() { int a[100]; int i,j,n,*ptr; printf("nEnter the elements of the arrayn"); scanf("%d",&n); printf("Enter the array elements"); for(i=0;i< n;i++) { scanf("%d",&a[i]); } printf("Array element are"); for(ptr=a;ptr<(a+n);ptr++) { printf("nValue of stored at address %u",ptr); } } 12
  • 13. Pointers • • • • • • • • • • • Multi-Dimensional Arrays int multi[ROWS][COLS]; we can access individual elements of the array multi using either: multi[row][col] or *(*(multi + row) + col) To understand more fully what is going on, let us replace *(multi + row) with X as in: *(X + col) Now, from this we see that X is like a pointer since the expression is de-referenced and we know that col is an integer. The arithmetic being used here is of a special kind called "pointer arithmetic". That means that, since we are talking about an integer array, the address pointed to by (i.e. value of) X + col + 1 must be greater than the address X + col by and amount equal to sizeof(int). 13
  • 14. Pointers • Since we know the memory layout for 2 dimensional arrays, we can determine that in the expression multi + row as used above, multi + row + 1 must increase by value an amount equal to that needed to "point to" the next row, which in this case would be an amount equal to COLS * sizeof(int). • That says that if the expression *(*(multi + row) + col) is to be evaluated correctly at run time, the compiler must generate code which takes into consideration the value of COLS, i.e. the 2nd dimension. Because of the equivalence of the two forms of expression, this is true whether we are using the pointer expression as here or the array expression multi[row][col]. 14
  • 15. Pointers • Thus, to evaluate either expression, a total of 5 values must be known: • The address of the first element of the array, which is returned by the expression multi, i.e., the name of the array. • The size of the type of the elements of the array, in this case sizeof(int). • The 2nd dimension of the array • The specific index value for the first dimension, row in this case. • The specific index value for the second dimension, col in this case. • Given all of that, consider the problem of designing a function to manipulate the element values of a previously declared array. For example, one which would set all the elements of the array multi to the value 1. 15
  • 16. Pointers • More on Strings • Well, we have progressed quite a way in a short time! Let's back up a little and look at what was done in Chapter 3 on copying of strings but in a different light. Consider the following function: char *my_strcpy(char dest[], char source[]) { int i = 0; while (source[i] != '') { dest[i] = source[i]; i++; } dest[i] = ''; return dest; } • • • • • • • • • • • • Recall that strings are arrays of characters. Here we have chosen to use array notation instead of pointer notation to do the actual copying. The results are the same, i.e. the string gets copied using this notation just as accurately as it did before. This raises some interesting points which we will discuss. • Since parameters are passed by value, in both the passing of a character pointer or the name of the array as above, what actually gets passed is the address of the first element of each array. Thus, the numerical value of the parameter passed is the same whether we use a character pointer or an array name as a parameter. This would tend to imply that somehow source[i] is the same as *(p+i). 16
  • 17. Pointers • Pointers to Functions • Up to this point we have been discussing pointers to data objects. C also permits the declaration of pointers to functions. Pointers to functions have a variety of uses and some of them will be discussed here. • Consider the following real problem. You want to write a function that is capable of sorting virtually any collection of data that can be stored in an array. This might be an array of strings, or integers, or floats, or even structures. The sorting algorithm can be the same for all. For example, it could be a simple bubble sort algorithm, or the more complex shell or quick sort algorithm. We'll use a simple bubble sort for demonstration purposes. • Sedgewick [1] has described the bubble sort using C code by setting up a function which when passed a pointer to the array would sort it. If we call that function bubble(), a sort program is described by bubble_1.c, which follow 17
  • 18. Pointers • /* Program bubble_3.c from PTRTUT10.HTM 6/13/97 */ • #include <stdio.h> • int arr[10] = { 3,6,1,2,3,8,4,1,7,2}; • • void bubble(int *p, int N); int compare(int *m, int *n); • • • • • int main(void) { int i; putchar(' '); • • • • • • • for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar(' '); • • • • • • } • • • • • • • • • • • • • • • • void bubble(int *p, int N) { int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { if (compare(&p[j-1], &p[j])) { t = p[j-1]; p[j-1] = p[j]; p[j] = t; } } } } for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; 18
  • 19. Pointers • • • • • • • • • • • #include<stdio.h> void main(){ int i = 3; int *j; int **k; j=&i; k=&j; printf(" %d ",**k); } Explanation: Memory representation 19
  • 20. Pointers • Here 6024, 8085, 9091 is any arbitrary address, it may be different. • Value of k is content of k in memory which is 8085 • Value of *k means content of memory location which address k keeps. • • • • • • • • • • k keeps address 8085 . Content of at memory location 8085 is 6024 In the same way **k will equal to 3. Short cut way to calculate: Rule: * and & always cancel to each other i.e. *&a = a So *k = *(&j) since k = &j *&j = j = 6024 And **k = **(&j) = *(*&j) = *j = *(&i) = *&i = i = 3 20