cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Size: px
Start display at page:

Download "cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];"

Transcription

1 1 C++ Dynamic Allocation Memory needs were determined before program execution by defining the variables needed. Sometime memory needs of a program can only be determined during runtime, or the memory needed depends on user input. On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete. // Example of program using dynamic memory int main() int memsize, n; int *p; cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize]; if (p == NULL) cout << "Error: memory could not be allocated"; else for (n=0; n < memsize; n++) cout << "Enter number: "; cin >> p[n]; cout << "You have entered: "; for (n=0; n < memsize; n++) cout << p[n] << ", "; delete[] p;

2 2 How many numbers would you like to type? 5 Enter number : 75 Enter number : 436 Enter number : 1067 Enter number : 8 Enter number : 32 You have entered: 75, 436, 1067, 8, 32, Memory in your C++ program is divided into two parts: 1. The stack: All variables declared inside the function will take up memory from the stack. 2. The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs. Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time. You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory previously allocated by new operator. Allocating memory There are two ways that memory gets allocated for data storage: Compile Time (or static) Allocation Memory for named variables is allocated by the compiler Exact size and type of storage must be known at compile time For standard array declarations, this is why the size has to be constant Dynamic Memory Allocation Memory allocated "on the fly" during run time dynamically allocated space usually placed in a program segment known

3 3 as the heap or the free store Exact amount of space or number of items does not have to be known by the compiler in advance. For dynamic memory allocation, pointers are crucial // Program to demonstrate the use of operator 'new' // and 'delete' to dynamically allocate memory in C++ int main() char *sp; int size; cout << How many characters to enter: ; cin >> size; sp = new char[size+1]; if (sp) cout << "String? "; cin.getline(sp, size+1); cout << "You entered: " << sp << endl; else cout << "Request failed\n"; return 1; delete[] sp; // delete Examples on the usage of 'new' operator // An expression to allocate a single char new char // An expression to allocate a single int new int

4 4 // An expression to allocate a single double new double // An expression to allocate a single pointer to a float new float* // One char char* ptr_char = new char; // One int int* ptr_int = new int; // One double double* ptr_double = new double; Using 'delete' operator to delete allocated memory int* ptr = new int ; delete ptr ; // delete the allocated memory int* ptr = new int[10] ; delete [] ptr ; // delete array or memories // How to initialize value when allocating memory char* ptr_char = new char('a') ; int* ptr_int = new int(65) ; float* ptr_float = new float(1.234) ; C++ struct Keyword and typedef Keyword #include <cstring> typedef struct char title[50]; char author[50]; char subject[100];

5 5 int Books; book_id; int main( ) Books Book1; // Declare Book1 of type Book // book1 specification strcpy( Book1.title, "Learn C++ Programming"); strcpy( Book1.author, "Chand Miyan"); strcpy( Book1.subject, "C++ Programming"); Book1.book_id = ; // Print Book1 info cout << "Book 1 title : " << Book1.title <<endl; cout << "Book 1 author : " << Book1.author <<endl; cout << "Book 1 subject : " << Book1.subject <<endl; cout << "Book 1 id : " << Book1.book_id <<endl; Book 1 title : Learn C++ Programming Book 1 author : Chand Miyan Book 1 subject : C++ Programming Book 1 id : Dynamic Memory Allocation for Objects Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept: class Box public: Box() cout << "" <<endl;

6 6 ; ~Box() cout << "" <<endl; int main( ) Box* myboxarray = new Box[4]; delete [] myboxarray; // Delete array If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times. If we compile and run above code, this would produce the following result:

Apllications. February 17, Indian Institute of Space Science and Technology. MA122 - Computer Programming and. Apllications. Structures.

Apllications. February 17, Indian Institute of Space Science and Technology. MA122 - Computer Programming and. Apllications. Structures. Indian Institute of Space Science Technology February 17, 2017 Lecture 14 1 2 3 Declaration 1 struct inflatable // structure declaration 2 { 3 char name[20]; 4 float volume; 5 double price; 6 }; ++ types

More information

Pointers II. Class 31

Pointers II. Class 31 Pointers II Class 31 Compile Time all of the variables we have seen so far have been declared at compile time they are written into the program code you can see by looking at the program how many variables

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

PASCAL - RECORDS. To define a record type, you may use the type declaration statement. The record type is defined as

PASCAL - RECORDS. To define a record type, you may use the type declaration statement. The record type is defined as http://www.tutorialspoint.com/pascal/pascal_records.htm PASCAL - RECORDS Copyright tutorialspoint.com Pascal arrays allow you to define of iables that can hold several data items of the same kind but a

More information

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am Exam 1 on July 18, 2005 10:00-11:40am 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. This is the

More information

Structures can be easily used as a function parameters. It is done similar as with variables.

Structures can be easily used as a function parameters. It is done similar as with variables. 1. Structures in functions. Structures can be easily used as a function parameters. It is done similar as with variables. #include char title[50]; char author[50]; char subject[100]; int book_id;

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation Lecture 15 COP 3014 Fall 2017 November 6, 2017 Allocating memory There are two ways that memory gets allocated for data storage: 1. Compile Time (or static) Allocation Memory

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 STRUCTURES STRUCTS Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available

More information

Stack memory - "scratch pad" memory that is used by automatic variables.

Stack memory - scratch pad memory that is used by automatic variables. Dynamic Memory Allocation In C and C++ three types of memory are used by programs: Static memory - where global and static variables live Stack memory - "scratch pad" memory that is used by automatic variables.

More information

Exam 3 Chapters 7 & 9

Exam 3 Chapters 7 & 9 Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

C/C++ Lab Sessions - COL 106

C/C++ Lab Sessions - COL 106 C/C++ Lab Sessions - COL 106 Last updated: 20 July 2014 This module is targeted to kick-start students in programming C/C++ by introducing them to the basic syntax and useful/essential features of C/C++.

More information

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain Duhok Polytechnic University Amedi Technical Institute/ IT Dept. By Halkawt Rajab Hussain 2016-04-02 : Structure declaration and initialization. Access to fields of structure. Array of Structs. 11/10/2016

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static

More information

C Programming Basics II

C Programming Basics II C Programming Basics II Xianyi Zeng xzeng@utep.edu Department of Mathematical Sciences The University of Texas at El Paso. September 20, 2016. Pointers and Passing by Address Upon declaring a variable,

More information

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31. Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172 The lab will be on pointers In compensation, no class on Friday, Jan. 31. 1 Consider the bubble function one more

More information

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2 Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the

More information

Launchpad Lecture -10

Launchpad Lecture -10 Saturday, 24 September Launchpad Lecture -10 Dynamic Allocation, Object Oriented Programming-1 Prateek Narang 2 Recap 1. How to define pointers? 2. Address of Operator? 3. Dereference operator? 4. Arithmetic

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

Pointers. Developed By Ms. K.M.Sanghavi

Pointers. Developed By Ms. K.M.Sanghavi Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create

More information

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

Polymorphism. Zimmer CSCI 330

Polymorphism. Zimmer CSCI 330 Polymorphism Polymorphism - is the property of OOP that allows the run-time binding of a function's name to the code that implements the function. (Run-time binding to the starting address of the code.)

More information

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

MM1_ doc Page E-1 of 12 Rüdiger Siol :21 Contents E Structures, s and Dynamic Memory Allocation... E-2 E.1 C s Dynamic Memory Allocation Functions... E-2 E.1.1 A conceptual view of memory usage... E-2 E.1.2 malloc() and free()... E-2 E.1.3 Create

More information

Structured Data. CIS 15 : Spring 2007

Structured Data. CIS 15 : Spring 2007 Structured Data CIS 15 : Spring 2007 Functionalia HW4 Part A due this SUNDAY April 1st: 11:59pm Reminder: I do NOT accept LATE HOMEWORK. Today: Dynamic Memory Allocation Allocating Arrays Returning Pointers

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Department of Computer Science and Engineering. Programming for Problem Solving. I Year B.Tech. (I - Sem) Assistant Professor (M.

Department of Computer Science and Engineering. Programming for Problem Solving. I Year B.Tech. (I - Sem) Assistant Professor (M. Website : www.aceec.ac.in ACE Engineering College Ankushapur, Ghatkesar, Telangana 501301 (EAMCET Code: ACEG) NAAC Accridated with A Grade Department of Computer Science and Engineering Programming for

More information

The University of Nottingham

The University of Nottingham The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, SPRING SEMESTER 2011-2012 G52CPP C++ Programming Examination Time allowed TWO hours Candidates may complete the front cover of

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Variables, Memory and Pointers

Variables, Memory and Pointers Variables, Memory and Pointers A variable is a named piece of memory The name stands in for the memory address int num; Variables, Memory and Pointers When a value is assigned to a variable, it is stored

More information

Unit 8. Structures and Unions. School of Science and Technology INTRODUCTION

Unit 8. Structures and Unions. School of Science and Technology INTRODUCTION INTRODUCTION Structures and Unions Unit 8 In the previous unit 7 we have studied about C functions and their declarations, definitions, initializations. Also we have learned importance of local and global

More information

CS24 Week 3 Lecture 1

CS24 Week 3 Lecture 1 CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation

More information

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4 The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 02 Example of Objective Test Questions for Test 4 True or False Name: 1. The statement switch (n) case 8 : alpha++; case

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli COMS W3101 Programming Language: C++ (Fall 2015) ramana@cs.columbia.edu Lecture-2 Overview of C continued C character arrays Functions Structures Pointers C++ string class C++ Design, difference with C

More information

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.

More information

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. The declaration below declares three pointer variables of type pointer to double that is

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

CS 115 Midterm 2 Review Quiz

CS 115 Midterm 2 Review Quiz CS115Midterm2ReviewQuiz November6,2008 Groupmembers: Rules Youmustbrieflyexplainyouranswerstoreceivepartialcredit. Whenasnippetofcodeisgiventoyou,youcanassumethatthecodeis enclosedwithinsomefunction,evenifnofunctiondefinitionisshown.you

More information

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli COMS W3101 Programming Language: C++ (Fall 2015) ramana@cs.columbia.edu Lecture-2 Overview of C continued C character arrays Functions Structures Pointers C++ string class C++ Design, difference with C

More information

C-types: basic & constructed. C basic types: int, char, float, C constructed types: pointer, array, struct

C-types: basic & constructed. C basic types: int, char, float, C constructed types: pointer, array, struct C-types: basic & constructed C basic types: int, char, float, C constructed types: pointer, array, struct Memory Management Code Global variables in file (module) Local static variables in functions Dynamic

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

C++ Structures Programming Workshop 2 (CSCI 1061U)

C++ Structures Programming Workshop 2 (CSCI 1061U) C++ Structures Programming Workshop 2 (CSCI 1061U) Faisal Qureshi http://faculty.uoit.ca/qureshi University of Ontario Institute of Technology C++ struct struct keyword can be used to define new data types

More information

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC CSCI 262 Data Structures 9 Dynamically Allocated Memory POINTERS AND ARRAYS 2 Arrays Arrays are just sequential chunks of memory: Arrays and Pointers Array variables are secretly pointers: x19 x18 x17

More information

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL Many programs require complex data to be represented That cannot easily

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Using pointers Pointers are polymorphic Pointer this Using const with pointers Stack and Heap Memory leaks and dangling pointers

More information

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova A reference (&) is like a constant pointer that is automatically dereferenced. There are certain rules when using references: 1. A reference must be initialized

More information

Programming in C++: Assignment Week 2

Programming in C++: Assignment Week 2 Programming in C++: Assignment Week 2 Total Marks : 20 Each question carries one mark Right hand side of each question shows its Type (MCQ/MSQ) March 3, 2017 Question 1 Look at the code snippet below:

More information

Computer Programming

Computer Programming Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Quiz and Practice Questions on Classes Part 1 Dr. Deepak B. Phatak & Dr. Supratik

More information

CSC 1300 Exam 4 Comprehensive-ish and Structs

CSC 1300 Exam 4 Comprehensive-ish and Structs CSC 1300 Exam 4 Comprehensive-ish and Structs December 8, 2017 Name: Read through the entire test first BEFORE starting Multiple Choice and T/F sections should be completed on the scantron Test has two

More information

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator C++ Addendum: Inheritance of Special Member Functions Constructors Destructor Construction and Destruction Order Assignment Operator What s s Not Inherited? The following methods are not inherited: Constructors

More information

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates Sebastian Wild Technische Universität München 11.01.2010 Abstract In this work we will discuss about templates in C++, especially their

More information

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University [CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9 Seungkyu Lee Assistant Professor, Dept. of Computer Engineering Kyung Hee University CHAPTER 9 Pointers #1~2 Pointer int main () { int a; int b; int c;

More information

CS 115 Exam 3, Spring 2010

CS 115 Exam 3, Spring 2010 Your name: Rules You must briefly explain your answers to receive partial credit. When a snippet of code is given to you, you can assume o that the code is enclosed within some function, even if no function

More information

Lab - 10 Write a c# program to prepend the namespace name by calling the namespaceenabled version of either function or variable?

Lab - 10 Write a c# program to prepend the namespace name by calling the namespaceenabled version of either function or variable? Lab - 10 Write a c# program to prepend the namespace name by calling the namespaceenabled version of either function or variable? namespace first_space class namespace_cl Console.WriteLine("Inside first_space");

More information

Computer Programming

Computer Programming Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Introduction to Pointers Part 1 Dr. Deepak B. Phatak & Dr. Supratik Chakraborty,

More information

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli COMS W3101 Programming Language: C++ (Fall 2016) ramana@cs.columbia.edu Lecture-2 Overview of C C++ Functions Structures Pointers Design, difference with C Concepts of Object oriented Programming Concept

More information

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1 Lab 2: Pointers 1. Goals Further understanding of pointer variables Passing parameters to functions by address (pointers) and by references Creating and using dynamic arrays Combing pointers, structures

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

Separate Compilation Model

Separate Compilation Model Separate Compilation Model Recall: For a function call to compile, either the function s definition or declaration must appear previously in the same file. Goal: Compile only modules affected by recent

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Homework Assignment #2 (revised)

Homework Assignment #2 (revised) CISC 2000 Computer Science II Fall, 2018 1 Recall the following functions and operators: Homework Assignment #2 (revised) sizeof function: returns the size of a variable (i.e., the number of bytes used

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management

More information

Linked Memory. Pointers Linked Lists. January 19, 2018 Cinda Heeren / Geoffrey Tien 1

Linked Memory. Pointers Linked Lists. January 19, 2018 Cinda Heeren / Geoffrey Tien 1 Linked Memory Pointers Linked Lists January 19, 2018 Cinda Heeren / Geoffrey Tien 1 Addresses and pointers Every storage location in memory (RAM) has an address associated with it The address is the location

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

CS250 Final Review Questions

CS250 Final Review Questions CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure that you review all previous exams and make sure you fully understand

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is? Discussion 1H Notes (Week 8, May 20) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 Dynamic Allocation of Memory Recall that when you create an array, you must know

More information

Tema 6: Dynamic memory

Tema 6: Dynamic memory Tema 6: Programming 2 and vectors defined with 2013-2014 and Index and vectors defined with and 1 2 3 and vectors defined with and and vectors defined with and Size is constant and known a-priori when

More information

C:\Temp\Templates. Download This PDF From The Web Site

C:\Temp\Templates. Download This PDF From The Web Site 11 2 2 2 3 3 3 C:\Temp\Templates Download This PDF From The Web Site 4 5 Use This Main Program Copy-Paste Code From The Next Slide? Compile Program 6 Copy/Paste Main # include "Utilities.hpp" # include

More information

The C++ Object Lifecycle. EECS 211 Winter 2019

The C++ Object Lifecycle. EECS 211 Winter 2019 The C++ Object Lifecycle EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/09lifecycle.tgz tar zx $ cd 09lifecycle 3 Road map Owned string type concept Faking it An owned string

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

CSE au Midterm Exam Nov. 2, 2018 Sample Solution Question 1. (16 points) Build tools and make. We re building a C++ software back-end prototype for a new food web site. So far, we ve got the following source files with the code for two main programs

More information

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ. C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,

More information

CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1]

CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1] CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define records (structures) that contain array data type as one of the

More information

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to:! Determine if a number is odd or even CS 2308 Fall 2018 Jill Seaman! Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

CSC1322 Object-Oriented Programming Concepts

CSC1322 Object-Oriented Programming Concepts CSC1322 Object-Oriented Programming Concepts Instructor: Yukong Zhang February 18, 2016 Fundamental Concepts: The following is a summary of the fundamental concepts of object-oriented programming in C++.

More information

2 2

2 2 1 2 2 3 3 C:\Temp\Templates 4 5 Use This Main Program 6 # include "Utilities.hpp" # include "Student.hpp" Copy/Paste Main void MySwap (int Value1, int Value2); int main(int argc, char * argv[]) { int A

More information

For Teacher's Use Only Q No Total Q No Q No

For Teacher's Use Only Q No Total Q No Q No Student Info Student ID: Center: Exam Date: FINALTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Time: 90 min Marks: 58 For Teacher's Use Only Q No. 1 2 3 4 5 6 7 8 Total Marks Q No. 9

More information

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable. CHAPTER 08 POINTERS What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable. The Pointers are one of the C++ s most useful and powerful features. How Pointers

More information

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

REFERENCES, POINTERS AND STRUCTS

REFERENCES, POINTERS AND STRUCTS REFERENCES, POINTERS AND STRUCTS Problem Solving with Computers-I https://ucsb-cs16-sp17.github.io/ Pointer assignment 2 int *p1, *p2, x; p1 = &x; p2 = p1; Q: Which of the following pointer diagrams best

More information

04-24/26 Discussion Notes

04-24/26 Discussion Notes 04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x

More information

Run Time Environment

Run Time Environment CS 403 Compiler Construction Lecture 12 Run Time Environment and Management [Based on Chapter 7 of Aho2] 1 Run Time Environment From Lecture 1 to 11, we have seen many jobs that are done by a compiler.

More information

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY Pages 800 to 809 Anna Rakitianskaia, University of Pretoria STATIC ARRAYS So far, we have only used static arrays The size of a static array must

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Chapter 9. Pointers and Dynamic Arrays

Chapter 9. Pointers and Dynamic Arrays Chapter 9 Pointers and Dynamic Arrays Overview 9.1 Pointers 9.2 Dynamic Arrays Slide 9-2 9.1 Pointers Pointers n A pointer is the memory address of a variable n Memory addresses can be used as names for

More information

Name. CPTR246 Spring '17 (100 total points) Exam 2

Name. CPTR246 Spring '17 (100 total points) Exam 2 Name CPTR246 Spring '17 (100 total points) Exam 2 1. Pointer parameters (the old C way) In the following program, make all of the changes to convert the call-by-reference parameters in the function computeoptions

More information

a data type is Types

a data type is Types Pointers Class 2 a data type is Types Types a data type is a set of values a set of operations defined on those values in C++ (and most languages) there are two flavors of types primitive or fundamental

More information

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allow for creation

More information

Linked Memory. Pointers Linked Lists. September 21, 2017 Cinda Heeren / Geoffrey Tien 1

Linked Memory. Pointers Linked Lists. September 21, 2017 Cinda Heeren / Geoffrey Tien 1 Linked Memory Pointers Linked Lists September 21, 2017 Cinda Heeren / Geoffrey Tien 1 Releasing Dynamic Memory When a function call is complete its stack memory is released and can be re-used Dynamic memory

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std; - 147 - Advanced Concepts: 21. Exceptions Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

More information