Presentation is loading. Please wait.

Presentation is loading. Please wait.

POINTERS.

Similar presentations


Presentation on theme: "POINTERS."— Presentation transcript:

1 POINTERS

2 3 Pointers i’s address in memory is a number. i int i=3
Reserve space in memory to hold the integer value. Associate the name i with this memory location. Store the value 3 at this location. 3 65524 i’s address in memory is a number.

3 & and * operators ‘&’ is used in C’s statement to provide ‘address of’ operator. The expression &i returns the address of the variable i * Provides value at address operator

4 Would This Work... int i = 10 ; j = &i ; j = &23 ; j = & ( i + 34 ) ;
& can be used only with a variable int i = 10 ; j = &i ; j = &23 ; j = & ( i + 34 ) ; * can be used with variable, constant or expression printf ( “ %d ” *j ) ; printf ( “ %d ”, *4568 ) ; printf ( “ %d ”, * ( ) ) ;

5 CONCATENATION OF TWO STRINGS USING POINTERS
void main(){   int i=0,j=0;   char *str1,*str2,*str3;   puts("Enter first string") ; gets(str1);   puts("Enter second string");  gets(str2);   printf("Before concatenation the strings are\n");   puts(str1); puts(str2); while(*str1){       str3[i++]=*str1++;   }   while(*str2){       str3[i++]=*str2++;   str3[i]='\0';   printf("After concatenation the strings are\n");   puts(str3);   }

6 Relevance of data type in pointer variable

7 Relevance of data type in pointer variable
An integer pointer (int *) points to an integer value only similarly for all data types. int *iP , i = 2; char *cP , c = ‘a’; Float *fP , f = 1.2; iP = &i; cP = &i; /* Error:Can not convert ‘int *’ to ‘char *’ */ fP = &c; /* Error:Can not convert ‘char *’ to ‘float *’ */ Note : Void pointer (void *) can point to any type of variable A Girl can point to a female personality only, and a boy can point to male personality.

8 Type Casting

9 Type Casting Typecasting is a way to make a variable of one type(such as an int), act like another type(such as a char), for one single operation. Syntax : (type)x : The value of x with specified type ANALOGY : MASK OF ANIMAL…..LION,MONKEY…..or A BOY or GIRL

10 Example : Type Casting #include <stdio.h> #include <stdlib.h> int main() { int i = 65; char c = (char)i; // This Typecast int to char Printf(“%c”,c); } /* The (char) is a typecast, telling the computer to interpret the 65 as a character, not as a number. It is going to give the character output of the equivalent of the number 65 (It should be the letter A for ASCII). Note that the %c below is the format code for printing a single character */ OUTPUT: A

11 Example :Pointer Type Casting
OutPut : *iP = 65 *cP = A void main() { int *iP,i=65; char *cP; iP = &i; //cP = iP; // Error : Can not convert 'int *' to 'char *' cP = (char *)iP; /* Type cast : 'int *' to 'char *‘ */ printf("\n\t*iP = %d",*iP); printf("\n\t*cP = %c",*cP); }

12 Pointer Constant

13 Constant Pointers  A constant pointer is a pointer that cannot change the address its holding. Constant pointer points to a variable then it cannot point to any other variable. SYNTAX: <type of pointer> * const <name of pointer> int * const ptr;

14 EXAMPLE #include<stdio.h> int main(void) {
int var1 = 0, var2 = 0; int *const ptr = &var1; ptr = &var2; printf("%d\n", *ptr); return 0; } OUTPUT: error: assignment of read-only variable ‘ptr’

15 Array of Pointers

16 Array of Pointers Pointers may be arrayed like any other data type.
The declaration for an int pointer array of size 10 is. int *ptr[10]; To assign the address of an integer variable ptr[2] = &var; To find the value of var, write *ptr[2]

17 If you want to pass an array of pointers into a function For ex,
void display_array(int *p[]) { int i; for(i=0 ; i<10 ; i++) printf(“%d”,*p[i]); } Note : Remember p is not a pointer to integer, but rather a pointer to an array of pointers to integer. Therefore you need to declare the parameter p simply as an array of integer pointers.

18 Pointer to Pointer

19 Pointer to Pointer You can have a pointer point to another pointer that points to the target value. This situation is called multiple indirection or pointer to pointer. Pointer Variable Address Value Single Indirection Pointer Pointer Variable Address Address Value Multiple Indirection

20 Example 1 : Pointers to Pointers
int a; int *p; int **q; a = 10; p = &a; q = &p; printf(“%d”, **q); // outputs 10

21 Passing Pointer to a function

22 Passing pointers to a functions
Engineering H192 Winter 2005 Passing pointers to a functions This is known as "call by reference" since we are referencing the variables. Instructor: Looking back as the swap function problem, the variable scope problem can now be solved by passing pointers, or the original location of variables, instead of just the values. The next slide explains more. Narrator: So now we can see how pointers can be used to pass addresses of variables around. They can also be used to pass addresses of variables to functions, thus allowing the function to alter the values of the original variables. Looking back at the swap function, you may remember it received copies of the variables, since they were called by value. Lecture 14

23 Call By Reference main( ) { int a = 10, b = 20 ; swap ( &a, &b ) ; printf ( "\na = %d b = %d", a, b ) ; } swap( int *x, int *y ) int t ; t = *x ; *x = *y ; *y = t ; Output : a = 20 b = 10 a b 10 20 412 111

24 main( ) { int a = 10, b = 20, c = 30 , s, p ; sumprod ( a, b, c, ) ; &s, &p printf ( ”%d%d”, s, p ) ; } sumprod ( int x, int y, int z, ) { } int *ss, int*pp p a b c s * ss = x + y + z ; 10 20 30 60 G 6000 G * pp = x * y * z ; 100 200 y pp x z ss 10 20 30 100 200

25 Example 2 :Pointers as Function Parameters
int main() { int x,y; int small,big; printf("Two integers: "); scanf("%d %d", &x, &y); min_max(x, y, &small, &big); printf("%d <= %d", small, big); return 0; } void min_max(int a, int b, int *min, int *max){ if(a>b){ *max=a; *min=b; } else{ *max=b; *min=a; you want a function that computes the minimum AND maximum numbers in 2 integers. Method 1, use two global variables. In the function, assign the minimum and maximum numbers to the two global variables. When the function returns, the calling function can read the minimum and maximum numbers from the two global variables. This is bad because the function is not reusable.

26 Returning a pointer from a function

27 int *f() : f is a function returning an int pointer
Declaration : int *f() : f is a function returning an int pointer Example : int *getMax(int *a , int *b); { if( *a > *b ) return a; else return b; }

28 Arithmetic and Logical Operations on Pointers

29 Arithmetic and Logical Operations on Pointers
Engineering H192 Winter 2005 Arithmetic and Logical Operations on Pointers A pointer may be incremented or decremented An integer may be added to or subtracted from a pointer. Pointer variables may be subtracted from one another. Pointer variables can be used in comparisons. Instructor: Most logical operations can be used on pointers as with regular variables, but the programmer must be careful of the results since each program doesn’t have free reign of the entire computer’s memory space. Errors which attempt to use memory not assigned to a certain program will cause what will be seen as a segmentation fault or bus error in UNIX, or Windows’ extreme, more deadly blue screen of death. Pointers can be incremented and decremented. Integers can be added or subtracted from a pointer, and pointers variable may be subtracted from one another. Pointers can also be used in comparisons, but usually only in a comparison to NULL as been shown when testing file pointers for a successful file open. Lecture 14

30 Pointer Arithmetic (1) int a[ 10 ], *p; p = &a[2]; *p = 10;
When a pointer variable points to an array element, there is a notion of adding or subtracting an integer to/from the pointer.elements int a[ 10 ], *p; p = &a[2]; *p = 10; *(p+1) = 20; printf("%d", *(p+3)); a[2] = 10; a[3] = 20; printf("%d", a[5]); When an integer is added to or subtracted from a pointer, the new pointer value is changed by the integer times the number of bytes in the data variable the pointer is pointing to. For example, if the pointer valptr contains the address of a double precision variable(of size 8) and that address is , then the statement: valptr = valptr + 2; would change valptr to p p+1 p+2 p+3 p+4 p+5 p+6 p+7 a a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

31 Pointer Arithmetic (2) int a[10], *p, *q; p = &a[2]; q = p + 3;
More examples: int a[10], *p, *q; p = &a[2]; q = p + 3; p = q – 1; p++; p--; *p = 123; *q = *p; q = p; scanf("%d", q) q points to a[5] now p points to a[4] now p points to a[5] now p points to a[4] now a[4] = 123 */ a[5] = a[4] q points to a[4] now scanf("%d", &a[4])

32 Pointer Arithmetic (3) int a[10], *p, *q , i; p = &a[2]; a[2]= 15;
If two pointers point to elements of a same array. int a[10], *p, *q , i; p = &a[2]; a[2]= 15; q = &a[5]; a[5]= 10; i = q - p; i = p - q; a[2] = a[5] = 0; i = *p - *q; p < q; p == q; p != q; // i is 3 // i is -3 // i = a[2] – a[5] // true // false // true

33 Pointers and Arrays

34 Pointers and Arrays Recall that the value of an array name is also an address. int a[11]; printf(“%d”,a); In fact, pointers and array names can be used interchangeably some cases. E.g. int n[2], *p; p=n; printf(“%d%d”,p,n); n[0]=10; printf(“%d%d”,*p,n[0]):

35 An Array Name is Like a Constant Pointer
Array name is like a constant pointer which points to the first element of the array. int a[10], *p, *q; p = a; // p = &a[0] q = a + 3; // q = &a[0 + 3] */ a ++; /* Error ( illegal !!! ) */ int a[ ] = { 5, 7, 8 , 2, 3 }; sum( a, 5 ); /* Equal to sum(&a[0],5) */ ……….

36 An Example //sum up elements of array int sum(int *ary, int size) {
int i, s; for(i = 0, s=0; i<size;i++){ s+=ary[i]; } return s; x= sum(&a[100],50); /* This sums up a[100], a[101], …, a[149] */

37 Dynamic Memory Allocation
Dynamic memory allocation in the C programming language is done via a group of functions in the C standard library, namely  malloc,  realloc,  calloc and  free

38

39


Download ppt "POINTERS."

Similar presentations


Ads by Google