POINTERS.

Slides:



Advertisements
Similar presentations
UNIT 9: Pointers Data Variable and Pointer Variable Pass by Reference
Advertisements

Lectures 10 & 11.
Programming and Data Structure
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Pointers in C Rohit Khokher
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Pointers Applications
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
UNIT 8 Pointers.
Pointers. Addresses in Memory Everything in memory has an address. C allows us to obtain the address that a variable is stored at. scanf() is an example.
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSC 215 Pointers and Arrays. Pointers C provides two unary operators, & and *, for manipulating data using pointers The operator &, when applied to a.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Lecture 5 Pointers 1. Variable, memory location, address, value
Arithmetic Expressions
CS1010 Programming Methodology
CS1010 Programming Methodology
Stack and Heap Memory Stack resident variables include:
User-Written Functions
Chapter 8 Arrays, Strings and Pointers
Computer Science 210 Computer Organization
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
UNIT 5 C Pointers.
Pointers.
Pointers and Pointer-Based Strings
C Short Overview Lembit Jürimägi.
INC 161 , CPE 100 Computer Programming
Programmazione I a.a. 2017/2018.
Lecture 6 C++ Programming
Andy Wang Object Oriented Programming in C++ COP 3330
Pointers.
Computer Science 210 Computer Organization
14th September IIT Kanpur
Object Oriented Programming COP3330 / CGS5409
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
Lecture 18 Arrays and Pointer Arithmetic
Programming with Pointers
Pointers.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Outline Defining and using Pointers Operations on pointers
Introduction to Problem Solving and Programming
Pointer Operations.
Pointers Pointers point to memory locations
Pointers and Pointer-Based Strings
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Data Structures and Algorithms Introduction to Pointers
Exercise Arrays.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Chapter 9: Pointers and String
Programming in C Pointers and Arrays.
Introduction to Pointers
Presentation transcript:

POINTERS

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.

& 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

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 ”, * ( 4568 + 1 ) ) ;

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

Relevance of data type in pointer variable

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.

Type Casting

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

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

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

Pointer Constant

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;

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’

Array of Pointers

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]

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.

Pointer to Pointer

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

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

Passing Pointer to a function

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

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

main( ) { int a = 10, b = 20, c = 30 , s, p ; sumprod ( a, b, c, ) ; &s, &p 60 6000 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

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.

Returning a pointer from a function

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

Arithmetic and Logical Operations on Pointers

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

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 234567870, then the statement: valptr = valptr + 2; would change valptr to 234567886 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]

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])

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

Pointers and Arrays

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]):

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) */ ……….

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] */

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