ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Names and Bindings.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Pointers Applications
LECTURE 4: INFORMATION REPRESENTATION (PART II) COMP26120: ALGORITHMS AND IMPERATIVE PROGRAMMING.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Lecture 2 Arrays, Pointers, and Structures. Objective In this chapter, we will discuss several concepts: Arrays (first-class arrays, using vector) Strings.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Microsoft Visual C++.NET Chapter 61 Memory Management.
Compiler Construction
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
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.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 3 – August 28, 2001.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 10 – September 20, 2001.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Engineering Computing I Chapter 5 Pointers and Arrays.
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.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
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.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
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.
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.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Java Review: Reference Types
Lecture 8 Data structures
MSIS 655 Advanced Business Applications Programming
SPL – PS2 C++ Memory Handling.
Presentation transcript:

ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001

ICOM 4035Dr. Manuel Rodriguez Martinez2 Readings Read Appendix D of textbook –Primitive Arrays in C++ Read chapter 1 of textbook –Arrays, pointers and structures Do not read section 1.6.3

ICOM 4035Dr. Manuel Rodriguez Martinez3 Built-in Arrays in C++ Arrays are one of the most fundamental constructs in any programming language. An array is a collection on N elements of the same data type. C++ array declaration: int size=5; int nums[size]; –Array of 5 elements –Run-time support system will provide block of contiguous memory large enough to accommodate it. New C++ standard comes with new array type –Vector – is a class with more features than basic array

ICOM 4035Dr. Manuel Rodriguez Martinez4 Built-in arrays in C++ (cont.) Suppose an array is initialized as follows: for (int i=0; i < size; ++i){ nums[i]= i * 2; } Result of this will be: Can have default initializers –char vowels[] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; –Initializes the array with 5 elements, each with the corresponding letter

ICOM 4035Dr. Manuel Rodriguez Martinez5 Built-in arrays in C++ (cont.) Compiler computes the space for the array when the default initializer is used. Arrays can be arguments to functions. A string is basically an array of char: –char name[] = “Manuel”; –This is equivalent to: char name[] = {‘M’, ‘a’, ‘n’, ‘u’, ‘e’, ‘l’, ‘\0’}; The ‘\0’ is the end of string character, thus the string has 7 characters, including the ‘\0’. –New C++ standard has a new string class with lots of features.

ICOM 4035Dr. Manuel Rodriguez Martinez6 Multi-dimensional arrays Multi-dimensional arrays: –int table[2][3] – two-dimensional array of with 2 row and 3 columns, for a total of 6 entries. –Addressing is more complicated Will need to variables to index elements –table[i,j] table[0,2] – access element on row 0, column 2 [0,0][0,1][0,2] [0,1]

ICOM 4035Dr. Manuel Rodriguez Martinez7 Function Calls: Call By Value In call by value, the value of the parameters are copied into temporary variables which are accessed by the statements in the body of the function. int sqr(int x){ return x * x; };... int y = 2, m = sqr(y); –The values of the parameter cannot be modified in the body of the function int sqr2(int x){ x *= x; return x; } … int y = 2, m = sqr2(y); The value of y still is 2 after the function call.

ICOM 4035Dr. Manuel Rodriguez Martinez8 Function Calls: Call ByReference In call by reference, a reference to the memory addresses of the parameters is passed to the statements in the function body. Avoids extra copy of values! int sqr(int& x){ return x * x; } … int y = 2, m = sqr(y); –The values of the parameter can be changed within the body of the function. int sqr2(int& x){ x*=x; return x; } … int y = 2, m = sqr2(y); Now, the value of variable y has become 4.

ICOM 4035Dr. Manuel Rodriguez Martinez9 Function Calls: Call By Constant Reference In call by constant reference, a constant reference to the memory addresses of the parameters is passed to the statements in the function body. Avoids extra copy of values! int sqr(const int& x){ return x * x; } … int y = 2, m = sqr(y); –The values of the parameter cannot be changed within the body of the function. int sqr2(const int& x){ x*=x; return x; } … int y = 2, m = sqr2(y); The value of variable y remains 2 after the function call.

ICOM 4035Dr. Manuel Rodriguez Martinez10 Structures in C++ Fundamental to build complex data structures. Provide the mechanism to represent multiple data values with a single data type. Consider a Person data type consisting of a name and age fields. Conceptually, we have: In C++ we can write: struct person{ char[100] name; int age; } name age Person

ICOM 4035Dr. Manuel Rodriguez Martinez11 Using Structures in C++ We can declare variables based on the types for the structures: struct person{ char[100] name; int age; } struct person student; –Now the variable student can be used to hold information about some person, which appear to be a student. Individual fields of the structure are access using the dot notation: –student.name – gives access to the name field –student.age – gives access to the age field. –Convention:.

ICOM 4035Dr. Manuel Rodriguez Martinez12 Typedef and Structures It is a good idea to create a type name for each structure because it makes your code more readable. –Use the typedef command for this purpose typedef struct person{ char[100] name; int age; } person; person student; –No need to add the word struct anywhere in the code

ICOM 4035Dr. Manuel Rodriguez Martinez13 Structures and functions Structures can be passed as arguments to functions –Use call-by-reference! pass the address of the structure –Call-by-value involves copying the whole structure into a temporary variable, thus there is too much overhead. –Examples void printPerson(person & thePerson){ // call-by-reference - efficient … } void printPerson(person thePerson){ // call-by-value  - inefficient, too much copying }

ICOM 4035Dr. Manuel Rodriguez Martinez14 Structures and Functions Return pointers to structures as the return value from a function. –Pointer created by calls to new operator. Returning the structure by value would be inefficient because the whole structure must be copied to a temporary variable. Do not return references or pointers to structures local to the function because these cease to exits upon return from the function. –Big bad bug in your program!

ICOM 4035Dr. Manuel Rodriguez Martinez15 Structures and Functions (cont.) Examples: person *makeNew(char[] name, int age){ person *result; result = new person; result->name = name; result->age = age; return result; } This returns a pointer to the structure. Usually the way to go! The notation -> replace the dot (.) notation since now the variable is a pointer.

ICOM 4035Dr. Manuel Rodriguez Martinez16 Structures and Functions (cont.) This mechanism is correct but somewhat inefficient person makeNew(char[] name, int age){ person result; result = new person; result.name = name; result.age = age; return result; } The return call will cause the value of result to be copied to another variable. If the structure has many fields, this would be very bad.

ICOM 4035Dr. Manuel Rodriguez Martinez17 Structures and Functions (cont.) This mechanism is incorrect person *makeNew(char[] name, int age){ person result; result = new person; result.name = name; result.age = age; return &result; } Variable result is destroyed upon the return call, so its address will go away. Thus, the pointer returned will be a pointer to nowhere. –This is a big bad bug!

ICOM 4035Dr. Manuel Rodriguez Martinez18 Rules of thumb for Structures Pass structures by reference, constant reference or as pointers to the functions. Return structures by values if they are small. Return pointers to structures as result of function calls if the structures are big.

ICOM 4035Dr. Manuel Rodriguez Martinez19 Pointers in C++ What is a pointer? –A pointer is a variable that stores the address of a memory location in which the data for another variable or object is stored. –A pointer can “point” to data that belongs to as simple variable (e.g. an int), an array, a structure or an object. Why do we need pointers? –Sometimes we cannot predict how many variables, or how much memory we might need to run our program. –Pointers provide the mechanism to allocate and deallocate memory in a dynamic fashion. Are we going to use pointers a lot in this course? –Yes.

ICOM 4035Dr. Manuel Rodriguez Martinez20 How big are pointers? All pointer are of the same size, since their value is an integer number that represents a memory location (a memory address). The size of a pointer will depend on the architecture of the underlying computer. A 32-bit architecture like Intel Pentium II has pointers of 32-bits (4-bytes). A 64-bit architecture like Sun Ultra SPARC has pointers of 64-bits (8-bytes). Typically the name of the locations addressed by pointers are termed “words”.

ICOM 4035Dr. Manuel Rodriguez Martinez21 Words? What are Words? Words are the minimal units of memory that the CPU can retrieve from the pool of bytes available in main memory. Why is this thing done? –Because it is inefficient for the CPU to be interrupted to bring just 1- byte. Therefore, computer architects and engineers came up with designs in which bytes were fetched from memory in groups. These groups are called words. –A 32-bit architecture brings bytes in groups of 4. –A 64-bit architecture brings bytes in groups of 8. Then, why can we have things like char, and short which are smaller than words? –The run-time system takes care of hiding the memory alignment from the programmer. –Structures, however, bring this ugly issue to the surface…

ICOM 4035Dr. Manuel Rodriguez Martinez22 Declaring pointer variables To declare a pointer variable, you must write the * symbol before the name of the variable: int x = 10, y = 20; // regular variables int *p; // pointer to an integer –Initially a pointer has no defined value, thus it points to an undefined memory location (BUG In Progress!) –One can initialize a pointer to a given location: int *p= &x; // gives p the address of x, Now p points to the location in which x is stored. –Changes made to a location via a pointer behave like changes made via the variable associate with the location. *p = 40; // now variable x has value 40 –The notation *p is used to access the value pointed by p. –In this case, the * is called the dereferencing operator.

ICOM 4035Dr. Manuel Rodriguez Martinez23 NULL pointer value Since a pointer initially points to an undefined location, it is always a good idea to initialize it to a well-known yet illegal memory location. This memory location is the 0 address, and in C++ we have a name for it: NULL. Golden Rule of Pointers: –If you don’t know what address to give a pointer at the moment of declaring it, then initialize it to NULL. –Example: int x = 10, y = 20; int *p = NULL; // safest thing on the planet

ICOM 4035Dr. Manuel Rodriguez Martinez24 Memory allocation with new To allocate a well-known and valid memory location to a pointer, you must use the new operator. int x = 10, y = 20; int *p = NULL; p = new int; *p = x + y; // gives *p the value 30 –It is also possible to initialize the value of the location pointed to by the pointer via the new operator: p = new int (17); This statement make *p equal to 17.

ICOM 4035Dr. Manuel Rodriguez Martinez25 Memory model: p vs. *p Remember that the value of the pointer is a memory location. The value of the “thing” pointed to by the pointer is the value stored at that memory location. In our example, p is a memory location, and *p is the value stored at the location pointed to by p. x = 10 y = 20 p = 2020 *p = 30 (&x) 2000 (&y) 2004 (&p) Memory addresses Values In memory