36
POINTERS

Pointers C programming

Embed Size (px)

Citation preview

Page 1: Pointers  C programming

POINTERS

Page 2: Pointers  C programming

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.

Page 3: Pointers  C programming

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.

Page 4: Pointers  C programming

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

Page 5: Pointers  C programming
Page 6: Pointers  C programming

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.

Page 7: Pointers  C programming

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

Page 8: Pointers  C programming
Page 9: Pointers  C programming
Page 10: Pointers  C programming
Page 11: Pointers  C programming
Page 12: Pointers  C programming
Page 13: Pointers  C programming
Page 14: Pointers  C programming
Page 15: Pointers  C programming
Page 16: Pointers  C programming
Page 17: Pointers  C programming
Page 18: Pointers  C programming
Page 19: Pointers  C programming

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.

Page 20: Pointers  C programming

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);}

Page 21: Pointers  C programming

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 wrongz = 5* - *p2 /*p1;

• The symbol /* is considered as the beginning of a comment

Page 22: Pointers  C programming

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

Page 23: Pointers  C programming

EXAMPLEmain(){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 = %d\n", p1);printf("Address of a = %d\n", p2);printf("\n");

printf("a = %d, b = %d\n", a, b);printf("x = %d, y = %d\n", x, y);*p2 = *p2 + 3;*p1 = *p2 - 5;z = *p1 * *p2 - 6;printf("\na = %d, b = %d,", a, b);printf(" z = %d\n",z);}OUTPUT:Address of a = 4020Address of b = 4016a = 12, b = 4x = 42, y = 9a = 2, b = 7, z = 8

Page 24: Pointers  C programming

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 likep1 = p1 + 2;p1 = p1 + 1;

• Expression likep1++;

• 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

Page 25: Pointers  C programming

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 elementint 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 xp = x;

Page 26: Pointers  C programming

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.

Page 27: Pointers  C programming

EXAMPLEmain(){int *p, sum, i;int x[5] = {5,9,6,2,7};i = 0; p = x;printf("Element Value Address\n\

n");while(i<5){printf(" x[%d] %d %d\n",i, *p, p);sum = sum + *p;i++; p++;}printf("\n Sum = %d\n", sum);printf("\n &x[0] = %d\n", &x[0]);printf("\n p = %d\n", p);}

OUTPUT:Element Value Addressx[0] 5 166x[1] 9 168x[2] 6 170x[3] 3 172x[4] 7 174Sum = 55&x[0] = 166p = 176

Page 28: Pointers  C programming

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)

Page 29: Pointers  C programming

POINTERS AND CHARACTER STRINGS• The strings are treated as character arrays and therefore they are

declared and initialized aschar 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:

Page 30: Pointers  C programming

• 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 asprintf(“%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

Page 31: Pointers  C programming

EXAMPLEmain(){char *name;int length;char *cptr = name;name = DELHI;printf("%s\n“,name);while(*cptr != '\0'){pritf("%c is stored at address %d\n", *cptr, cptr);cptr++;}length = cptr - name;printf("\nLength of the string = %d\n", length);}

OUTPUT:DELHID is stored at address 54E is stored at address 55L is stored at address 56H is stored at address 57I is stored at address 58

Length of the string = 5

Page 32: Pointers  C programming

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.

Page 33: Pointers  C programming

EXAMPLEmain(){int x;x = 20;change(&x);printf("%d\n",x);}change(int *P){*P = *P + 10;}OUTPUT:30

Page 34: Pointers  C programming

Pointers with Functions (example)void swap ( int *, int * ) ;main ( ){ int a = 5, b = 6; printf(“Before Swapping : a=%d b=%d\n",a,b) ; swap (&a, &b) ; printf(“After swapping : a=%d b=%d\n",a,b) ;} void swap( int *a, int *b ){ int temp; temp= *a; *a= *b; *b = temp ;}

Results:Before Swapping : a=5 b=6After Swapping : a=6 b=5

Page 35: Pointers  C programming

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);}

Page 36: Pointers  C programming

THE END