Upload
rohit-rbr
View
218
Download
0
Embed Size (px)
Citation preview
8/8/2019 PSC -- Lec 6
1/34
1
Pointers
8/8/2019 PSC -- Lec 6
2/34
2
Pointers Main memory is a sequence of memory locations
that are addressed 0, 1, 2, Pointers are variables that contain memory addresses
as their values. A pointer containing an address of some location is
said to be a pointer to that location. A pointer variable can have NULL (or 0) value
meaning that the pointer does not point to any
memory location. Zero is the only integer value that can be assigned to
a pointer. Size of pointer is often 4 bytes
8/8/2019 PSC -- Lec 6
3/34
3
Concept of Address and Pointers Memory can be
conceptualized as alinear set of data
locations.
Variables reference thecontents of a locations
Pointers have a value of
the address of a givenlocation
Contents1
Contents11
Contents16
ADDR1
ADDR2
ADDR3
ADDR4
ADDR5ADDR6
***
ADDR11
**
ADDR16
8/8/2019 PSC -- Lec 6
4/34
4
Pointers Pointers are variables that contain memory
addresses as their values.
A variable name directly references a value.
A pointer indirectly references a value.Referencing a value through a pointer is
called indirection. A pointer variable must be declared before it
can be used.
8/8/2019 PSC -- Lec 6
5/34
5
Accessing the address of a variable
We can obtain the value of address of thevariable stored using address operator (&).
The value thus obtained is known as pointervalue. The variable that contains pointer value is
called as pointer variable Form:
p = &q;
& (address of operator) can be used with avariable and array element
8/8/2019 PSC -- Lec 6
6/34
6
Accessing the address of a variable
Example:
#include int j, k;int *ptr;void main(void)
{j = 1;k = 2;ptr = &k;clrscr();printf("\n");printf("j has the value %d and is stored at %u\n", j, &j);
printf("k has the value %d and is stored at %u\n", k, &k);printf("ptr has the value %p and is stored at %u\n", ptr, &ptr);getch();
}/*Output:j has the value 1 and is stored at 978k has the value 2 and is stored at 976
ptr has the value 03D0 and is stored at 974*/
8/8/2019 PSC -- Lec 6
7/34
7
Declaring Pointer variable Pointer variables contain addresses that belong to a
separate data type, they must be declared aspointers before we use them.
Form:
data_type *pt_name
This tells the compiler about pt_name:1. The asterisk (*) tells that variable pt_name is a pointer
variable2. pt_name needs a memory location
3. pt_name points to a variable of type data_type.
8/8/2019 PSC -- Lec 6
8/34
8
Pointer declarations Examples: int *a; // integer pointer
float*b; // float pointerchar *c; //character pointer
The asterisk, when used as above in the declaration, tells thecompiler that the variable is to be a pointer, and the type ofdata that the pointer points to, butNOT the type of the value ofthe pointer.
This declarations cause the memory to allocate memorylocations for pointer variable (a, b, c). Since memory locationshave not been assigned by any values, these locations maycontain some unknown values in them and therefore they pointto the unknown location.
?a ?
Containsgarbage
Points to
unknownlocation
int *a;
8/8/2019 PSC -- Lec 6
9/34
9
Initialization of pointer variable The process of assigning the address of variable to a pointer variable is
known as initialization. Once the pointer variable is declared we can use the assignment
operator to initialize the variable. Example:
int q;Int *p; //Declaration
P=&q; //Initialization
OR
int x,*p=&q; //three in one. Valid
int *p=&q,x; Invalid
We can define pointer variable with initial value of NULL or 0 (zero) No other constant value can be assigned to pointer variable.Eg: int *p=NULL; Valid
int *p=0; Validint *p=5360; Invalid
8/8/2019 PSC -- Lec 6
10/34
10
Accessing a variable through its pointer
This is done by asterisk operator
It is also called as indirection operator
dereferencing operator * : Value at address
Example: p=&q;
n= *p;
n=*&q;
n=q;Note: You can not access the value stored at the address 5368 by just *5368
8/8/2019 PSC -- Lec 6
11/34
11
Example// program to demonstrate the use of pointers# includevoid main(){
int number=0;int *ptr;clrscr();printf("\n Enter number:");scanf("%d", &number);ptr=&number;printf("\n %d is stored at %u",number,ptr);
getch();}/*OutputEnter number:2323 is stored at 65524*/
8/8/2019 PSC -- Lec 6
12/34
12
Chain of pointers It is possible to make pointer to point another pointer.
Example:main(){Int x, *p1, **p2;
X=100;P1=&x;P2=&p1;Printf(%d,**p2);}
address2 address1 address1
p2 p1 Variable
8/8/2019 PSC -- Lec 6
13/34
13
Pointer Expression Like variables, pointer variables can be used in expression.// Pointer arithmeticvoid main(){
int a=0, b=0, *p1, *p2;clrscr();printf("\n Enter first number:");scanf("%d", &a);printf("\n Enter second number:");scanf("%d", &b);p1=&a; p2=&b;
printf("\n %d is at %u and %d is at %u", a,p1,b,p2);printf("\n p1-p2= %d " , p1-p2);printf("\n *p1 + *p2=%d ", *p1 + *p2);printf("\n *p1*5= %d", *p1*5);printf("\n*p1/*p2= %d", *p1/ *p2);printf("\n *p1/5= %d", *p1/5);printf("\n p1++ =%u",++p1);
getch();
/*Output:Enter first number:25Enter second number:2025 is at 65524 and 20 is at 6552p1-p2= 1
*p1 + *p2=45*p1*5= 125*p1/*p2= 1*p1/5= 5p1++ =65526 */
8/8/2019 PSC -- Lec 6
14/34
14
Arithmetic and Logical Operations on Pointers
A pointer may be incremented or decremented
An integer may be added to or subtracted from apointer.
Pointer variables may be subtracted from oneanother.
Pointer variables can be used in comparisons, butusually only in a comparison to NULL.
8/8/2019 PSC -- Lec 6
15/34
15
Arithmetic Operations on Pointers
When an integer is added to or subtracted from apointer, the new pointer value is changed by theinteger times the number of bytes in the datavariable the pointer is pointing to.
For example, if the pointer valptr contains theaddress of a double precision variable and that
address is 870, then the statement:valptr = valptr + 2;
would change valptr to 878
8/8/2019 PSC -- Lec 6
16/34
16
sizeof Thiskeyword can be used to determine the number
of bytesin a data type, a variable, or an array
Example:double array [10];
sizeof (double); /* Returns the value 8 */
sizeof (array); /* Returns the value 80 */
sizeof(array)/sizeof(double); /* Returns 10 */
8/8/2019 PSC -- Lec 6
17/34
17
Pointers and arrays When array is declared, the compiler allocates a
base address and sufficient amount of memorystorage to contain all the members of array in
contiguous memory locations. Base address is a location of first element in an
array (index 0) The compiler also defines the array name as
constant pointer to first element.
Eg: int x[5]={1,2,3,4,5}; Assume base address of x is 1000. Each integer
requires 2 bytes. The five elements can be storedas:
X[0] X[1] X[2] X[3] X[4]
1 2 3 4 5
1000 1002
1004 1006 1007
Elements
value
addressBase address
8/8/2019 PSC -- Lec 6
18/34
18
Pointers and arrays If p is declared as constant pointer pointing to first element
x[0] and therefore value of p is 1000p=&x[0]=1000
Pointer p is declared as pointer to an array: int p = &x[0]; Now we can access each value of x using p++ shown as:
P=&x[0] (=1000)P+1=&x[1] (=1002)P+2=&x[2] (=1004)P+3=&x[3] (=1006)P+4=&x[4] (=1008)
Adress of an element can be calculated:address of x[3] = base address + (3*scale factor of int)
1000+(3*2)=1006
8/8/2019 PSC -- Lec 6
19/34
19
Example#include
void main(){
char *c , ch[10];int *i , j[10];float *f , g[10];int x;clrscr();c = ch;i = j;
f = g;
for ( x=0 ; x
8/8/2019 PSC -- Lec 6
20/34
20
Example program to accept array elements and print them
with there address locations using pointers.
8/8/2019 PSC -- Lec 6
21/34
21
// program to accept array elements and
print them using pointers.void main(){int arr[5],i=0;int *ptr;clrscr();for(i=0;i
8/8/2019 PSC -- Lec 6
22/34
22
Pointers and character strings
void main() {char *ptr;char arrayChars[8] = {'F','r','i','e','n','d','s','\0'};clrscr();ptr = arrayChars;printf("The array reads %s.\n", arrayChars);*ptr = 'f'; /* ptr points to the first element */printf("now it reads %s.\n", arrayChars);printf("The 3rd character of the array is %c.\n",*(ptr+=2));
getch();}/*Output:The array reads Friends.now it reads friends.The 3rd character of the array is i.*
8/8/2019 PSC -- Lec 6
23/34
23
Program to copy one string into anotherstring; pointer version
8/8/2019 PSC -- Lec 6
24/34
24
/*strcpy: copy t to s; pointer version */
#includevoid main(){char arr[] = {'A','B','C','D'};char arr1[10];
char *s, *t;clrscr();s = arr;t = arr1;while ((*t = *s) != '\0'){
s++;t++;
}printf("%s",arr1);getch();}//ABCD
8/8/2019 PSC -- Lec 6
25/34
25
Array of pointers One important use while handling the
table of stringsEg: char name [3] [25];
Name contains three names with maximum length of25 caharacters.
Storage required is 75 bytes
We know that individual string will be of equal lengths.
Therefore, making each row a fixed number of characters, we can meke ita pointer to a string of varying length.
Eg: char * name [3] ;
8/8/2019 PSC -- Lec 6
26/34
26
Array of pointers# includevoid main(){char *str[5]={"Keyboard",
"Monitor","CPU" ,"Hard disk","SMPS"};
int i=0;clrscr();
for(i=0;i
8/8/2019 PSC -- Lec 6
27/34
27
Pointers as function arguments// Addition of two numbers using call by reference.
int add(int *, int*);# includemain()
{int a=0,b=0;clrscr();printf("\n Enter first number:");scanf("%d", &a);printf("\n Enter second number:");scanf("%d",&b);printf("\nAddition = %d",add(&a,&b));getch();}int add(int *x, int *y){return *x+*y;}
8/8/2019 PSC -- Lec 6
28/34
28
Pointer to function#include
int add(int x, int y); /* declare function */
void main() {
int x=6, y=9;int (*ptr)(int, int); /* declare pointer to function*/clrscr();ptr = add; /* set pointer to point to "add" function */
printf("%d plus %d equals %d.\n", x, y, (*ptr)(x,y));/* call function using pointer */getch();
}
int add(int x, int y) { /* function definition */return x+y;}//6 plus 9 equals 15
8/8/2019 PSC -- Lec 6
29/34
29
Passing array to function using pointer#includevoid zero_cnt(int *);void main(){
int arr[5], *p;int i=0;clrscr();for(i=0;i
8/8/2019 PSC -- Lec 6
30/34
30
Pointer and structurevoid main(){struct movie{char movie_nm[20];
char actor[15];int rel_year;};struct movie *ptr;clrscr();printf("\n Enter movie_nm:");scanf("%s", ptr->movie_nm);
printf("\n Enter movie actor:");scanf("%s", ptr->actor);printf("\n Enter release year:");scanf("%d",&ptr->rel_year);printf("\n Movie name - %s", ptr->movie_nm);printf("\n Actor-%s",ptr->actor);printf("\n Release year-%d",ptr->rel_year);
getch();
/*Output:Enter movie_nm: chamatkarEnter movie actor:sridevi
Enter release year:1986
Movie name - chamatkarActor-srideviRelease year-1986 */
8/8/2019 PSC -- Lec 6
31/34
31
Reference variable in C++ References allow you to create a second
name for the a variable that you can use toread or modify the original data stored in thatvariable.
A reference variable must be initialized at thetime of declaration.
A reference variable provides an alias for
previously defined variable Form:data_type & reference name = variable_name
8/8/2019 PSC -- Lec 6
32/34
32
//Demo of Reference variable#include#includevoid main(){
clrscr();float total=100;float &sum=total;
cout
8/8/2019 PSC -- Lec 6
33/34
33
Difference between Pointer
and Reference1. A pointer can be re-assigned any
number of times while a reference can
not be reassigned after initialization.
2. A pointer can point to NULL whilereference can never point to NULL
3. There's no "reference arithmetics
http://www.student.cs.uwaterloo.ca/~cs343/documents/refvsptr.html
8/8/2019 PSC -- Lec 6
34/34
34