19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Lectures 10 & 11.
Programming and Data Structure
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.
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.
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:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
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 Ethan Cerami Fundamentals of Computer New York University.
Introduction to C Programming CE
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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
Computer Skills2 for Scientific Colleges 1 Pointers in C++ Topics to cover: Overview of Pointers Pointer Declaration Pointer Assignment Pointer Arithmetic.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
21-2 Understand various methods of sorting. Use the qsort function to sort. Binary search Related Chapter: ABC 8.5.
Pointers CSE 2451 Rong Shi.
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:
16&17-2 Grasp the concept of top-down programming Identify Function Headers and Prototypes Understand when and where prototypes used Understand how arguments.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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:
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
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.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Review 1 List Data Structure List operations List Implementation Array Linked List.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
POINTERS. // Chapter 3 - Program 1 - POINTERS.CPP #include int main() { int *pt_int; float *pt_float; int pig = 7, dog = 27; float x = , y = 32.14;
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Lecture 10: 2/17/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter 6.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
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.
Chapter 7 Pointers and C-Strings
Standard Version of Starting Out with C++, 4th Edition
Lecture 6 C++ Programming
Object Oriented Programming COP3330 / CGS5409
Chapter 9: Pointers.
Lecture 18 Arrays and Pointer Arithmetic
Programming with Pointers
C Programming Lecture-8 Pointers and Memory Management
Chapter 9: Pointers and String
Chapter 9: Pointers and String
Pointers.
Presentation transcript:

19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC 6.2 – 6.6, 6.8, 6.10, 6.11, 6.15

19&20-3 Pointer variables are variables that store memory addresses. Pointers variables are useful in passing storage addresses in function calls (call-by-reference) and for applications involving dynamic data structures (e.g., linked lists) Example: int *intPtr; float *floatPtr; declares intPtr to be a pointer variable to an object of type integer. and floatPtr to be a pointer variable to an object of type float. The data type for intPtr is, int *,read as “pointer to an int”. The data type for floatPtr is, float *,read as “pointer to a float”.

19&20-4 We can write the pointer variable declaration as int* intPtr; or as int * intPtr; Note that when we declare more than two pointer variables in one line each pointer name requires an asterisk: int *ptr1, *ptr2; otherwise we are just declaring a regular variable, not a pointer variable.

19&20-5 There are two C operators that are necessary when using pointer variables. & - the address operator returns the address of a variable x ptrX 1000 ptrX holds the address of x. We say ptrX “points” to x. We will apply the & operator only to variables, e.g. &77 or &(x+1) are not valid. The declaration of ptrX initializes the variable ptrX = &x; Example: int x = 3; int * ptrX = &x; 1004

19&20-6 Example: int x; int * pt; pt = &x; /* another way to assign an address to a pointer variable */ Suppose the address of the variable x is 9640 Then, the effect of pt = &x; will be: xpt Address 9640

19&20-7 int x; int * pt; pt = &x; To assign the value “3” to the variable x in C: x = 3; We can use the “ * ” operator to indirectly reference x. We can assign “3” to x by: *pt = 3; Here we use the fact that “pt” points to integer values. x pt Address * - means "a pointer to" and is called an indirection operator or dereferencing operator, since a pointer "indirectly" references a value in a storage location. Example:

19&20-8 double *ptr; ptr = NULL; Assigning a NULL value (zero) to a pointer A null pointer points to nothing. We often depict it as ptr /*called a null pointer*/

19& Problem Definition Write a function “swap” that has two input integer arguments. This function should swap the values of the variables. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = two integers Output= no value is returned to the calling function, but the values of the called variables should be swapped. 3. Develop Algorithm Pass the addresses of the variables and not their values. In the swap function the parameters that hold the addresses are pointers. Use the indirection operator to swap the values.

19&20-10 /* C Function to swap values. */ #include void swap(int *, int *); void main(void) /* function header */ { int x = 1; int y = 2; swap(&x,&y); /* pass the addresses of x and y */ printf("x = %i, y = %i \n",x,y); /* prints x = 2, y = 1 */ } void swap(int *ptrX, int *ptrY) /* pointer variables */ { int temp = *ptrX; *ptrX = *ptrY ; *ptrY = temp; }

19&20-11 x 1000 Address Main Memory before call to swap 1 y 2 Main Memory while executing swap, after temp = *ptrX; but before *ptrX = *ptrY ; 1000 Address 1 ptrX x y ptrY temp 1

19&20-12 x y Main Memory while executing swap, after *ptrX = *ptrY ; but before *ptrY = temp; 1000 Address 2 ptrX ptrY temp 1

19&20-13 x y Main Memory while executing swap, after *ptrY = temp; but before return; 1000 Address 2 ptrX ptrY temp 1

19& Problem Definition Write a program that reads a list of real numbers into an array from the keyboard (or a file using Unix redirection). The array can be of arbitrary length but the user must first specify the length of the array. The program then calculates the average value, and then prints a list of differences. The differences are computed by taking the original values in the list minus the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = Since the length of the array is specified at run- time we must use Dynamic Memory Allocation. This is accomplished in C by the use of the built-in function calloc (or malloc). Use data-type double to hold the values. Output= The average and the list of differences.

#include void main(void) { int k,num; double * datValptr; /* pointer used in DMA */ double datAve; double sum = 0.0; /* prompt the user for the number of array elements */ printf("Please enter the number of array elements:"); scanf("%i",&num); /* use calloc to allocate a block of memory */ datValptr = calloc(num,sizeof(double)); /* verify that calloc was successful */ if (datValptr = = NULL) { printf("Memory not allocated!\n"); return; } (continued on next slide)

/* read the values and compute the average */ k = 0; for(k=0;k<num;++k) { scanf("%lf", &datValptr[k]);/* use pointer as array name */ sum += datValptr[k]; } /* compute the average */ datAve = sum /num; printf("The average is:%f \n", datAve); /* compute and print the diff list */ for(k=0;k<num;++k) { printf("%f\n", datValptr[k]-datAve); } /* end of for*/ /* free up any memory that was dynamically allocated */ free(datValptr); } /* end of main */

19&20-17 unixprompt>./a.out Please enter the number of array elements: The average is: unixprompt>

19&20-18 The array name in C is assigned the address of the first element of the array. The following code will assign the address of x[0] to xPtr : float x[50]; float * xPtr; xPtr = x; The assignment statement above is equivalent to: xPtr = &x[0];

19&20-19 In C, we can dynamically allocate storage with either of the following two functions (both are in ). malloc(numberOfBytes) calloc(numberOfItems, itemSize) Both functions return a pointer to the address of the block of storage that has been allocated. If no memory is available, a NULL value will be returned. Function calloc returns a contiguous block of locations that are initialized to 0 and that can be referenced as array locations, using pointer operations.

19&20-20 In both cases above (calloc or malloc) return memory locations to the system ("memory manager") with: free (ptr); Example: Declare ptr as a pointer variable to data- type double and use dynamic memory allocation (calloc or malloc) to allocate 100 elements of data- type double. double * ptr; ptr = calloc(100,sizeof(double)); or ptr = malloc(100*sizeof(double));

19&20-21 A string literal (e.g. “A – your course grade\n”) is actually represented in C by a pointer to an address in memory that holds the first byte of the array of characters. Therefore the following declaration of the pointer variable “string” is valid: char * string = "A – your course grade\n"; and to print the value of “string”, use the “%s” conversion specifier, printf("%s",string); Although a pointer can be used as an array name, we cannot modify the values of “string” by using the square brackets of array notation. string[0] = ‘B’; /* error !!! */ The error is due to the fact that the literal “A – your course grade\n” is stored in a location in memory that cannot be accessed by pointers.

19&20-22 One use of char * pointers is ragged arrays. In lecture we used the following code fragment to declare and initialize the array “morse” as : typedef char string[5]; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." }; An alternative would be the use of a ragged “morse” array declared as: typedef char * string; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };

19&20-23 The later declaration of the array “morse” is called ragged since each element of the array, morse[0], morse[1], … takes up exactly the number of bytes necessary in memory to hold the initialized strings whereas in the previous declaration of “morse” each element of the array takes exactly five character values in memory no matter what length of the initializing string. As discussed on slide 21, we cannot change the values of the ragged “morse” array. But in the “Morse Code” problem we know that the morse strings should never be changed.