1 Pointers. Variable Memory Snapshot 2 int nrate = 10; The variable is stored at specific memory address A variable is nothing more than a convenient.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Dynamic memory allocation
Lectures 10 & 11.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Pointers in C Rohit Khokher
BBS514 Structured Programming (Yapısal Programlama)1 Pointers.
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
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.
Engineering Problem Solving with C Fundamental Concepts Chapter 6 Pointers.
Kernighan/Ritchie: Kelley/Pohl:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Pointers Applications
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Lesson 9 Pointers CS 1 Lesson 9 -- John Cole1. Pointers in Wonderland The name of the song is called ‘Haddock’s Eyes’.” “Oh, that’s the name of the song,
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified by use by the MSU CMPS Dept. Chapter 10:
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Review 1 List Data Structure List operations List Implementation Array Linked List.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Windows Programming Lecture 03. Pointers and Arrays.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
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.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Standard Version of Starting Out with C++, 4th Edition
Chapter 9: Pointers.
INC 161 , CPE 100 Computer Programming
CSCE 210 Data Structures and Algorithms
Lecture 6 C++ Programming
An Introduction to Pointers
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Chapter 9: Pointers.
Pointers Problem Solving & Program Design in C Eighth Edition
Programming with Pointers
Standard Version of Starting Out with C++, 4th Edition
CISC181 Introduction to Computer Science Dr
Pointers.
Presentation transcript:

1 Pointers

Variable Memory Snapshot 2 int nrate = 10; The variable is stored at specific memory address A variable is nothing more than a convenient name for a memory location

3 Address Operator A variable can be referenced using the address operator & example: scanf(“%f”, &x); This statement specifies that the value read is to be stored at the address of x

4 Pointer Variables A pointer is a variable that holds the address of a memory location If a variable p holds the address of another variable q, then p is said to point to q If q is a variable at location 100 in memory, then p would have the value 100 (q’s address) 100 pq 200

5 How to declare a pointer variable pointer variables are declared using an asterisk ( * ) The asterisk is called the indirection operator or the de- referencing operator). example: int a, b, *ptr; ptr is a pointer to an integer when a pointer is defined, the type of variable to which it will point must be specified. (i.e. a pointer defined to point to an integer cannot also point to a floating point variable.)

6 Example int *iPtr; double* dPtr; the variable iPtr is declared to point to an int the variable dPtr is declared to point to a double neither variable has not been initialized in the above example declaring a pointer creates a variable capable of holding an address

Why Pointers? They allow you to refer to large data structures in a compact way They facilitate sharing between different parts of programs They make it possible to get new memory dynamically as your program is running They make it easy to represent relationships between data items 7

8 Example ? ? ? iPtr s dPtr int a, *iPtr; char* s; double *dPtr; ? a

9 More about declaring pointers When using the form int* p, q; the * operator does not distribute. In the above example p is declared to be a pointer to int. q is declared to be an int.

10 Assigning values to a pointer the assignment operator (=) is defined for pointers the right operand can be any expression that evaluates to the same type as the left the operator & in front of an ordinary variable produces the address of that variable. The operator * in front of a pointer variable returns the contents stored at that address

11 Example int i=6, j; int *iPtr; iPtr = &i; j = *iPtr; 6 6 i j iPtr

12 Exercise int a, b; int *c, *d; a = 5; c = &a; d = &b; *d = 9; print c, *c, &c print a, b ? ? ? ? memory a b c addressname c=1 *c=5 &c=4 a=5 b=9 5 1 d 2 9

13 Exercise Give a memory snapshot after each set of assignment statements int a=1, b=2, *ptr; ptr = &b; int a=1, b=2, *ptr=&b; a = *ptr;

14 NULL pointer A pointer can be assigned or compared to the integer zero, or, equivalently, to the symbolic constant NULL, which is defined in. A pointer variable whose value is NULL is not pointing to anything that can be accessed

15 Example iPtr s dPtr int *iPtr=0; char *s=0; double *dPtr=NULL;

16 Pointer Assignments A pointer can point to only one location at a time, but several pointers can point to the same location. /* Declare and initialize variables. */ int x=-5, y = 8, *ptr1, *ptr2; /* Assign both pointers to point to x. */ ptr1 = &x; ptr2 = ptr1; The memory snapshot after these statements are executed is ptr1 ptr2 xy -58

17 Pointer Arithmetic Four arithmetic operations are supported +, -, ++, -- only integers may be used in these operations Arithmetic is performed relative to the variable type being pointed to Example:p++; if p is defined as int *p, p will be incremented by 4 (system dependent) if p is defined as double *p, p will be incremented by 8(system dependent when applied to pointers, ++ means increment pointer to point to next value in memory

18 Comparing Pointers You may compare pointers using relational operators Common comparisons are: check for null pointer (p == NULL) check if two pointers are pointing to the same object  (p == q) Is this equivalent to  (*p == *q) compare two pointers that are pointing to a common object such as an array.

19 Exercise int x=2, y=3, temp; int *ptr1, *ptr2, *ptr3; // make ptr1 point to x ptr1 = &x; // make ptr2 point to y ptr2 = &y; Show the memory snapshot after the following operations 2 x 5 y ? temp ptr1 ptr2ptr3

20 Exercise // swap the contents of // ptr1 and ptr2 ptr3 = ptr1; ptr1 = ptr2; ptr2 = ptr3; Show the memory snapshot after the following operations 2 x 5 y ? temp ptr1 ptr2ptr3

21 Exercise // swap the values pointed // by ptr1 and ptr2 temp = *ptr1; *ptr1 = *ptr2; *ptr2 = temp; Show the memory snapshot after the following operations 5 x 2 y 5 temp ptr1 ptr2ptr3

22 Two Dimensional Arrays A two-dimensional array is stored in sequential memory locations, in row order. Array definition:int s[2][3] = {{2,4,6}, {1,5,3}}, *sptr=&s; Memory allocation: s[0][0]2 s[0][1]4 s[0][2]6 s[1][0]1 s[1][1]5 s[1][2]3 A pointer reference to s[0][1] would be *(sptr+1) A pointer reference to s[1][1] would be *(sptr+4) row offset * number of columns + column offset

23 Pointers in Function References In C, function references are call-by-value except when an array name is is used as an argument. An array name is the address of the first element Values in an array can be modified by statements within a function To modify a function argument, a pointer to the argument must be passed The actual parameter that corresponds to a pointer argument must be an address or pointer.

24 Call by Value void swap(int a, int b) { int temp; temp = a; a = b; b = temp; return; }

25 Call by Value int x = 2, y = 3; printf("X = %d Y = %d\n",x,y); swap(x,y); printf("X = %d Y = %d\n",x,y); Changes made in function swap are lost when the function execution is over

26 Call by reference void swap2(int *aptr, int *bptr) { int temp; temp = *aptr; *aptr = *bptr; *bptr = temp; return; }

27 Call by reference int x = 2, y = 3; int *ptr1, *ptr2; ptr1 = &x; ptr2 = &y; swap2(ptr1,ptr2); printf("X = %d Y = %d\n",*ptr1,*ptr2); x = 2; y = 3; swap2(&x,&y); printf("X = %d Y = %d\n",x,y); Version 1 Version 2

28 Exercise Write a function to compute the roots of quadratic equation ax^2+bx+c=0. void comproots(int a,int b,int c,double *dptr1, double *dptr2) { *dptr1 = (-b - sqrt(b*b-4*a*c))/(2.0*a); *dptr2 = (-b + sqrt(b*b-4*a*c))/(2.0*a); return; }

29 Exercise int a,b,c; double root1,root2; printf("Enter Coefficients:\n"); scanf("%d%d%d",&a,&b,&c); computeroots(a,b,c,&root1,&root2); printf("First Root = %lf\n",root1); printf("Second Root = %lf\n",root2);

Exercise Implement a function increaseanddouble(…) which takes 2 integers and increases the value of first by 1 and doubles the value of the second x=3;y=5; … printf(“x=%d y=%d\n“,x,y); increaseanddouble(…); printf(“x=%d y=%d\n“,x,y); x=3 y=5 x=4 y=10 OUTPUT

31 Exercise void function3(int a, int b) { int temp; temp = a; a = b; b = temp; printf("A = %d, B = %d\n",a,b); return; } ab 1 temp 2 Function 3 variables

32 Exercise int x = 1, y = 2; printf("X = %d, Y = %d\n",x,y); function3(x,y); printf("X = %d, Y = %d\n",x,y); 12 xy

33 Exercise void function4(int *pa, int *pb) { int temp; temp = *pa; *pa = *pb; *pb = temp; printf("PA = %d, PB = %d\n",*pa,*pb); return; } pb 1 pa temp Function 4 variables 2

34 Exercise int x = 1, y = 2; int *px = &x, *py = &y; x = 1; y = 2; printf("PX = %d, PY = %d\n",*px,*py); function4(px,py); printf("PX = %d, PY = %d\n",*px,*py); 12 xy pxpy

35 Exercise void function1(int a, int *pb) { int temp; temp = a; a = *pb; *pb = temp; printf("A = %d, PB = %d\n",a,*pb); return; } a 2 pb 1 temp Function 1 variables

36 Exercise int x = 1, y = 2; int *px = &x, *py = &y; printf("X = %d, PY = %d\n",x,*py); function1(x,py); printf("X = %d, PY = %d\n",x,*py); 12 xy pxpy

37 Exercise void function2(int *pa, int b) { int temp; temp = *pa; *pa = b; b = temp; printf("PA = %d, B = %d\n",*pa,b); return; } b 1 pa 2 temp Function 2 variables

38 Exercise int x = 1, y = 2; int *px = &x, *py = &y; x = 1; y = 2; printf("PX = %d, Y = %d\n",*px,y); function2(px,y); printf("PX = %d, PY = %d\n",*px,y); 12 xy pxpy

39 Pointers and Arrays The name of an array is the address of the first elements (i.e. a pointer to the first element) The array name is a constant that always points to the first element of the array and its value can not be changed. Array names and pointers may often be used interchangeably. Example int num[4] = {1,2,3,4}, *p; p = num; /* above assignment is the same as p = &num[0]; */ printf(“%i”, *p); p++; printf(“%i”, *p);

40 More Pointers and Arrays You can also index a pointer using array notation Example: char string[] = “This is a string”; char *str; int i; str = string; for(i =0; str[i]; i++)//look for null printf(“%c”, str[i]);

41 Dynamic Memory Allocation Dynamically allocated memory is determined at runtime A program may create as many or as few variables as required, offering greater flexibility Dynamic allocation is often used to support data structures such as stacks, queues, linked lists and binary trees. Dynamic memory is finite Dynamically allocated memory may be freed during execution

42 Dynamic Memory Allocation Memory is allocated using the: malloc function(memory allocation) calloc function (cleared memory allocation) Memory is released using the: free function The size of memory requested by malloc or calloc can be changed using the: realloc function

43 malloc and calloc Both functions return a pointer to the newly allocated memory If memory can not be allocated, the value returned will be a NULL value The pointer returned by these functions is declared to be a void pointer A cast operator should be used with the returned pointer value to coerce it to the proper pointer type #include to use these functions

44 Example of malloc int n = 6, m = 4; double *x; int *p; /* Allocate memory for 6 doubles. */ x = (double *)malloc(n*sizeof(double)); To free the space allocated use free() free(x); X

45 calloc (allocate memory for arrays) int m = 4; int *p; /* Allocate memory for 4 integers. */ p = (int *)calloc(m,sizeof(int)); p[0]=2; p[1]=3; To free the space allocated use free() free(x); p

46 Realloc (change size of memory) int m = 4; int *p; /* Allocate memory for 4 integers. */ p = (int *)calloc(m,sizeof(int)); /* change the size of memory block pointed by p */ q = realloc(p,2*m*sizeof(int)); To free the space allocated use free() free(x); p

47 Dynamic Data Structures Grow and shrink during the execution of a program. Memory is allocated and freed as neded. Pointers are used to connect the data. Examples: Linked list Doubly Linked List Queue Binary Tree

48 Linked List Group of nodes connected by pointers A node consists of Data Pointer to next node HeadNull

49 Insertion into a Linked List Insert 18 in sorted order HeadNull 18

50 Deletion from a Linked List Delete 21 from the list HeadNull 18 Free this space

51 Declaration of a node struct node { int data; struct node *link; } HeadNull

52 Print a linked list void printlist(struct node *head) { struct node *next; if (head == NULL) printf(“Empty List\n”); else { printf(“List Values: \n”); next = head; while (next->link != NULL) { printf(“%d \n”,next->data); next = next -> link; } printf(“%d \n”,next->data); } return; } HeadNull