Arrays and Pointers Reference: Chapter 4.1-4.8, 4.11 CMSC 202.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Lecture 20 Arrays and Strings
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.
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Chapter 10.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
C pointers (Reek, Ch. 6) 1CS 3090: Safety Critical Programming in C.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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.
Pointers CSE 2451 Rong Shi.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
Pointer Data Type and Pointer Variables. Objectives: Pointer Data Type and Pointer Variables Pointer Declaration Pointer Operators Initializing Pointer.
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 and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
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.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
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.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Pointers and Dynamic Arrays
EGR 2261 Unit 11 Pointers and Dynamic Variables
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Day 03 Introduction to C.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
Pointers and Memory Overview
Arrays in C.
Lecture 6 C++ Programming
8 Pointers.
Pointers and References
Object-Oriented Programming Using C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers and Dynamic Variables
7 Arrays.
Chapter 9: Pointers.
Pointers, Dynamic Data, and Reference Types
Constant pointers and pointers to constants
Pointers and Pointer-Based Strings
Lecture 18 Arrays and Pointer Arithmetic
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
C++ Pointers and Strings
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
Exercise Arrays.
Chapter 9: Pointers and String
Standard Version of Starting Out with C++, 4th Edition
CISC181 Introduction to Computer Science Dr
C++ Pointers and Strings
Pointers, Dynamic Data, and Reference Types
4.1 Introduction Arrays A few types Structures of related data items
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Arrays and Pointers Reference: Chapter 4.1-4.8, 4.11 CMSC 202

A data type that groups many related data items of the Array A data type that groups many related data items of the same type for easy processing A complex (aggregate, composite) data type A homogeneous data type Elements occupy contiguous memory locations Pointer A value that points to the location (contains the address of) another value A simple data type Typically stored as four bytes Arrays and pointers have a very intimate relationship in C++. CMSC 202

Array Declaration and Initialization Sample Declarations int x[5]; // 5 integer elements float z[16]; // 16 float elements char str[20]; // 20 character elements char* c[16]; // 16 character pointer elements Sample Initializations int x[5] = {2, -8, 0, 10, 29}; // all elements initialized int y[] = {2, -8, 0, 10, 29}; // space automatically allocated float z[16] = {2.5, 8.9}; // remaining elements = 0.0 char str[20] = “Hello”; // str[5] = ‘\0’ CMSC 202

Pointer Declaration and Initialization Sample Declarations int* xPtr; // integer pointer char* chPtr; // character pointer Vector* vPtr; // Vector object pointer Sample Initializations int x; int* xPtr = &x; // contains address of (points to) integer x char ch = ‘$’; char* chPtr = &ch; // points to character ch Vector v; Vector* vPtr = &v; // points to object v CMSC 202

Relationship Between Arrays and Pointers An array name used with a subscript refers to a particular element int x[10]; cout << x[8]; // displays contents of 9th element An array name used without a subscript refers to the address of the first element of the array int x[10;] cout << x; // displays the address of x[0] Therefore, in this example, x is the same as &x[0]. Note that x cannot be used as an lvalue. CMSC 202

Pointer Operations Assignment Comparison Pointers of the same type can be assigned to one another Pointers of different types can be assigned only with an explicit type cast The NULL pointer (usually zero) can be assigned to a pointer of any type Comparison Pointers of the same type can be compared using the relational operators ==, !=, <, >, <=, and >= CMSC 202

Pointer Operations (continued) Indirection (Dereferencing) int x = 5; int* xPtr = &x; cout << x; // displays 5 cout << &xPtr; // displays address of xPtr cout << xPtr; // displays value of xPtr (address of x) cout << *xPtr; // displays 5 (value of x) int** xPtrPtr = &xPtr; // double indirection cout << &xPtrPtr; // displays address of xPtrPtr cout << xPtrPtr; // displays value of xPtrPtr (address of xPtr) cout << *xPtrPtr; // displays value of xPtr (address of x) cout << **xPtrPtr; // displays 5 (value of x) CMSC 202

Pointer Operations (continued) Pointer (Address) Arithmetic pointer + integer int* x; // assume 4-byte integer char ch; // assume 1-byte char x+=3; // increments x by 4*3=12 bytes ch+=5; // increments ch by 1*5=5 bytes pointer - integer Analogous to pointer + integer pointer - pointer double *a, *b; // assume 8-byte double x = b - a; // x is the integer difference between b and a // in memory CMSC 202

Pointer Operations (continued) Indexing A pointer p, whether an array name or a pointer variable, can be subscripted. char p[10]; char* p; p[3] = ‘a’; p[3] = ‘a’; // same as *(p+3) Be careful! In the second case, you may be overwriting memory that you shouldn’t be! CMSC 202

Passing Pointer Arguments Example int strcmp(const char *r, const char *x) { // notice const while (*r == *s) { // dereferencing if (*r == ‘\0’) // dereferencing return(0); r++; s++; // pointer arithmetic } return(*r - *s); // dereferencing Note that the function header could have been int strcmp(const char r[], const char x[]) CMSC 202

Functions Returning Pointers A function may return a pointer to a data type Example char* strcpy(char *s, const char *cs) { // notice const char* tmp = s; while (*cs != ‘\0’) *(tmp++) = *(cs++); // copy the character *tmp = ‘\0’; // don’t forget null terminator! return(s); // returns a pointer to the string copied to } Calling strcpy: char str1[20], str2[10] = “CMSC 202”; cout << strcpy(str1, str2); // make sure str1 is big enough! CMSC 202

Pointers and Dynamically Allocated Storage The declaration of an array is static int x[100]; // x always has 100 elements, even if // not all are needed An array can be dimensioned dynamically by the use of a pointer to the array and the new operator int* x = new int[someInt]; // someInt = integer expression Here, the array will only be as large as is needed (no “guestimating” the maximum size needed). Example - next slide CMSC 202

Pointers and Dynamically Allocated Storage (Continued) class Person { // static implementation public: Person(); void setLastName(char []); void setfirstName(char []); char* getLastName(); char* getFirstName(); private: char lastName[20]; // last name cannot exceed 20 characters char firstName[15]; // first name cannot exceed 15 characters }; Person p1, p2; // These objects will have the size of their last and // first names limited to 20 and 15, respectively CMSC 202

Pointers and Dynamically Allocated Storage (Continued) // static implementation Person::Person() { lastName[0] = ‘\0’; firstName[0] = ‘\0’; } void Person::setLastName(char last[]) { strcpy(lastName, last); // Last must be able to fit into lastName! } // Error check would be appropriate. void Person::setFirstName(char first[]) { strcpy(firstName, first]; // first must be able to fit into firstName! char* Person::getLastName() {return(lastName);} char* Person::getFirstName() {return(firstName);} CMSC 202

Pointers and Dynamically Allocated Storage (Continued) class Person { // dynamic implementation public: Person(); void setLastName(char *); // note: could still use char[] void setfirstName(char *); char* getLastName(); char* getFirstName(); private: char* lastName; // Storage for first and last names will be char* firstName; // allocated dynamically }; Person p1, p2; // These objects can have first and last names of // different sizes CMSC 202

Pointers and Dynamically Allocated Storage (Continued) // dynamic implementation Person::Person() { lastName = firstName = NULL; // set name pointers to NULL } void Person::setLastName(char last[]) { // dynamic allocation lastName = new char [strlen(last) + 1]; strcpy(lastName, last); void Person::setFirstName(char first[]) { // dynamic allocation firstName = new char[strlen(first) + 1]; strcpy(firstName, first); char* Person::getLastName() {return(lastName);} // no change char* Person::getFirstName() {return(firstName);} // no change CMSC 202

Using arrays of pointers can save storage space Example typedef char Str10[10]; // define a string type of length 10 Str10 daysOfWeek[7]; // array to hold names of days of week strcpy(daysOfWeek[0], “Sunday”); strcpy(daysOfWeek[6], “Saturday”); Storage is wasted on days of the week that are less than 9 characters in length. (“Wednesday” is the longest with 9 characters.) CMSC 202

Arrays of Pointers (continued) Using an array of pointers will save space char* daysOfWeek[7]; daysOfWeek[0] = new char[strlen(“Sunday”)+1]; strcpy(daysOfWeek[0], “Sunday”); daysOfWeek[0] = new char[strlen(“Saturday”)+1]; strcpy(daysOfWeek[0], “Saturday”); Notice that the strings in the array can be of different lengths, thereby wasting no storage space. CMSC 202