Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.

Slides:



Advertisements
Similar presentations
Kernighan/Ritchie: Kelley/Pohl:
Advertisements

Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
Chapter 10.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
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.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
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.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
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.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Dynamic memory allocation and Pointers Lecture 4.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 3 – August 28, 2001.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Computer And Programming Array and Pointer. Array provides a means to allocating and accessing memory. Pointers, on the other hand, provides a way to.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Variables and memory addresses
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT9: Pointer I CS2311 Computer Programming.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
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.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
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.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Computer Organization and Design Pointers, Arrays and Strings in C
Standard Version of Starting Out with C++, 4th Edition
Chapter 9: Pointers.
CNG 140 C Programming (Lecture set 10)
Lecture 6 C++ Programming
Dynamic Memory Allocation Reference Variables
Dynamic Memory Allocation
Chapter 9: Pointers.
Pointers, Dynamic Data, and Reference Types
Lecture 18 Arrays and Pointer Arithmetic
C Programming Lecture-8 Pointers and Memory Management
CS250 Introduction to Computer Science II
Standard Version of Starting Out with C++, 4th Edition
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming

Outline 2 Access array elements via pointers Manage strings via pointers Dynamic memory allocation

The NULL pointer 3 A special value that can be assigned to any type of pointer variable (e.g., int *a=NULL; double*b=NULL;) A symbolic constant defined in several standard library headers, e.g. When assigned to a pointer variable, that variable points to nothing Example int *ptr1 = NULL; int *ptr2 = 0;

Operations on pointers 4 Copying the address p = q; p and q points to the same variable Copying the content Copy the value of the variable which is pointed by the p to the variable which is pointed by q *p = *q; p and q may point to different variables.

Copy the address Assignment: p = q; 5 We copy the content (which is an address) of q to p. After the assignment, p and q point to the same location in memory. Therefore, if we change *p, *q will also be changed

Copy the content *p = *q; 6 We copy the value of the variable pointed by q to the variable pointed by p. After the assignment, p and q still point to different locations in memory. if we change *p, *q will not be changed as p and q points to different location in memory.

Relationship between arrays and pointers int num[2]={40,50}; num[0]=400; num[1]=500; int num[2]={40,50}; int *p=num; p[0]=400; p[1]=500; Equivalent to We can use array-like notation in pointers num is a constant pointer to the first byte of the array; p is a pointer variable; and thus the value of p can be changed. p=num; However, the value of num cannot be changed. num=p; /*illegal*/

Relationship between arrays and pointers int num[2]={40,50}; int *p; p=num; p[0]=400; p[1]=500; int num[2]={40,50}; int *p; p=num; /* p points to 90 *p=400; ++p; /*p points to 94 */ *p=500; Equivalent to ++p increments the content of p (an address) by sizeof(int) bytes

Arrays and pointers Equivalent representationRemark num&num[0] num is the address of the 0th element of the array num+i&(num[i]) Address of the ith element of the array *numnum[0] The value of the 0th element of the array *(num+i)num[i] The value of the ith element of the array (*num)+inum[0]+i The value of the 0th element of the array plus i 9

Example 2: summing an array #define N 10 void main() { } 10 a+0 is the address of a[0] a+1 is the address of a[1]... a+i is the address of a[i] So, *(a+i) means a[i] int a[N]={1,2,3,4,5,6,7,8,9,10}; int sum = 0; for(int i = 0; i < N; ++i) sum+=*(a+i);//sum+=a[i]; cout << sum;/*55 is printed*/

Passing arrays to functions 11 When an array is being passed, its base address is passed; the array elements themselves are not copied  This is call-by-reference As a notational convenience, the compiler allows array bracket notation to be used in declaring pointers as parameters, e.g. double sum(int *a); is the same as double sum(int b[]);

double sum(int *b) { int i; double total = 0.0; for (i=0; i<N; i++) total += b[i]; return total; } Example 3: Parameter Passing #define N 5 double sum(int *b); void main() //Compute the mean value { int a[N] = {8,6,2,7,1}; double mean; mean = sum(a)/N; cout << "mean = “ << mean; } When sum(a) is called, the content of a (address of a[0]) is copied to the pointer variable b. Therefore the pointer b points to a[0] a b

Arrays, pointers and strings char s[]="abc"; s="abcd"; //illegal Illegal as s is a constant pointer and cannot be modified 13

cin >> a string (I) char s[]="abc"; cin >> s; 14 input: “Hello World”

cin >> a string (I) 15 Size of s is 4. Array out-of-bound! cin >> does not perform bound- checking Better to use: cin.getline(s,4); /*read at most 3 characters*/ Leaving space for the final '\0' character

cin >> a string (II) #include using namespace std; void main () { char *s1; cin >> s1; cout << s1<<endl; } 16 Problem: when we declare the pointer s1, we do not know where s1 points to. In this example, we try to read a string and store it in the location pointed by s1. This may generate errors as we may overwrite some important locations in memory

Dynamic memory allocation #include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); cin >> s1; cout << s1; delete [] s1; s1=NULL; } 17

Dynamic memory allocation #include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); cin >> s1; cout << s1; delete [] s1; s1=NULL; } 18 new dynamically allocates 4 bytes of memory. new returns a pointer to the 1st byte of the chunk of memory, which is assigned to s1

Example 4: Dynamic memory allocation #include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); //same as char[6] cin >> s1; cout << s1; delete [] s1; s1=NULL; } 19

Example 4: Dynamic memory allocation 20 #include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); //same as char[6] cin >> s1; cout << s1; delete [] s1; s1=NULL; } Memory is free and can be used to store other data

#include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); //same as char[6] cin >> s1; cout << s1; delete [] s1; s1=NULL; } new dynamically allocates 6 bytes of memory. new returns a pointer to the 1st byte of the chunk of memory, which is assigned to s1

#include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); //same as char[6] cin >> s1; cout << s1; delete [] s1; s1=NULL; }

#include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); //same as char[6] cin >> s1; cout << s1; delete [] s1; s1=NULL; }

#include void main () { char *s1=NULL; s1=new char[4]; cin >> s1; /*input "abc"*/ cout << s1; delete [] s1; s1=new char(6); //same as char[6] cin >> s1; cout << s1; delete [] s1; s1=NULL; }

Guidelines on using pointers 25 Initialize a pointer to NULL after declaration char *cPtr=NULL; Check its value before use if (cptr!=NULL){ …. } Free the memory allocated by the “new” operator using delete cPtr = new char[6]; … delete [] cPtr; Set it NULL again after free delete [] cPtr; cPtr = NULL;

Summary 26 Pointers can be used to access array element. Array name is a pointer pointing to the first element of the array. A string is stored as an array of characters. Strings must be terminated by an ‘\0’ character (e.g., a string with 5 characters will take up 6 characters space). Operator new allocates memory space and returns a pointer pointing to the newly allocated space. Memory obtained by new must be deleted after use. Extra care must be taken when handling pointers, as it may point to an invalid / unexpected location and make the program crashed.