MAFS 5240 C++ Basics Arrays & Pointers

Size: px
Start display at page:

Download "MAFS 5240 C++ Basics Arrays & Pointers"

Transcription

1 MAFS 5240 C++ Basics Arrays & Pointers Arrays Pointers 1 Arrays holds a collection of objects of some type arrays are fixed size; new elements cannot be added individual objects are not named; each one is accessed by its position arrays should be restricted to the internals of programs and used only where performance testing indicates that vectors cannot provide the necessary speed 2

2 An Array 3 Arrays - Defining a compound type that consists of a type specifier, an identifier, and a dimension dimension must be a constant expression whose value is greater than or equal to one constant expression integral literal constants enumerators const objects of integral type that are themselves initialized from constant expressions nonconst variable, or a const variable whose value is not known until run time, cannot be used to specify the dimension of an array 4

3 Array - Defining // both buf_size and max_files are const const unsigned buf_size = 512, max_files = 20; int staff_size = 27; // nonconst const unsigned sz = get_size(); // const value not known // until run time char input_buffer[buf_size]; // ok: const variable string filetable[max_files + 1]; // ok: constant expression double salaries[staff_size]; // error: non const variable int test_scores[get_size()]; // error: non const expression int vals[sz]; // error: size not known // until run time 5 Subscripting Accessing an Array Element 6

4 Example 7 Array - Initialize Elements of an array of built-in type defined outside the body of a function are initialized to zero Elements of an array of built-in type defined inside the body of a function are uninitialized Regardless of where the array is defined, if it holds elements of a class type, then the elements are initialized by the default constructor for that class if it has one. If the class does not have a default constructor, then the elements must be explicitly initialized 8

5 Initialization 9 Array - Initialize int ia[] = {0, 1, 2}; // an array of dimension 3 const unsigned array_size = 5; // Equivalent to ia[] = {0, 1, 2, 0, 0} // ia[3] and ia[4] default initialized to 0 int ia[array_size] = {0, 1, 2}; // Equivalent to str_arr = {"hi", "bye", "", "", ""} // str_arr[2] thru str_arr[4] default initialized to empty string string str_arr[array_size] = {"hi", "bye"}; char ca1[] = {'C', '+', '+'}; // no null char ca2[] = {'C', '+', '+', '\0'}; // explicit null char ca3[] = "C++"; // null terminator added automatically const char ch3[6] = "Daniel"; // error: Daniel is 7 elements 10

6 No Array copy or assignment int ia[] = {0, 1, 2}; // ok: array of ints int ia2[](ia); // error: cannot initialize one array // with another int main() { const unsigned array_size = 3; int ia3[array_size]; // ok: but elements are uninitialized! ia3 = ia; // error: cannot assign one array to another return 0; } 11 Copying one array to another // right type to use for the index is size_t const size_t array_size = 7; int ia1[] = { 0, 1, 2, 3, 4, 5, 6 }; int ia2[array_size]; // local array, elements uninitialized // copy elements from ia1 into ia2 for (size_t ix = 0; ix!= array_size; ++ix) ia2[ix] = ia1[ix]; By far, the most common causes of security problems are so-called "buffer overflow" bugs. These bugs occur when a subscript is not checked and reference is made to an element outside the bounds of an array or other similar data structure. 12

7 Pointers A pointer points to an object of some other type Pointers are iterators for arrays: A pointer can point to an element in an array Dereference a pointer obtain the object to which the pointer points Increment a pointer advance the pointer to denote the next element in the array 13 Pointers Pointer holds the address of another object string s("hello world"); string *sp = &s; // sp holds the address of s & operator in &s is the address-of operator when dereferenced yields the original object Pointers and arrays are surprisingly errorprone. Modern C++ programs should use vectors and iterators to replace general arrays and strings to replace C-style arraybased character strings. 14

8 Pointers - Defining Every pointer has an associated type The * symbol in a declaration to indicate that an identifier is a pointer vector<int> *pvec; // pvec can point to a vector<int> int string *ip1, *ip2; // ip1 and ip2 can point to an int *pstring; // pstring can point to a string double *dp; // dp can point to a double 15 Pointers - Initialization & Assignment a constant expression with value 0 address of an object of an appropriate type address one past the end of another object another valid pointer of the same type int ival; int zero = 0; const int c_ival = 0; int *pi = ival; // error: pi initialized from int value pi = zero; // error: pi assigned int value of zero pi = c_ival; // ok: c_ival is a const with compile- // time value of 0 pi = 0; // ok: initialize to literal constant 0 16

9 Pointers - Initialization & Assignment // cstdlib #defines NULL to 0 int *pi = NULL; // ok: equivalent to int *pi = 0; double dval; double *pd = &dval; // ok: address of a double double *pd2 = pd; // ok: a pointer to double int *pi = pd; // error: types of pi and pd differ pi = &dval; // error: assign address of double to int * 17 Show Pointers 18

10 Void* Pointers a special pointer type that can hold an address of any object double obj = 3.14; double *pd = &obj; void *pv = &obj; pv = pd; // obj can be an object of any type // pd can be a pointer to any type 19 Avoid Uninitialized Pointers Results in run-time error when we attempt to dereference the uninitialized pointer Can be hard to track down No way to distinguish a valid address from an address formed from the bits that are in the memory in which the pointer was allocated Best practices do not define a pointer until the object to which it should point has been defined initialize the pointer to zero 20

11 Pointers - Dereference 21 Pointers and References reference always refers to an object; an error to define a reference without initializing it assigning to a reference changes the object to which the reference is bound; it does not rebind the reference to another object. Once initialized, a reference always refers to the same underlying object. int ival = 1024, ival2 = 2048; int *pi = &ival, *pi2 = &ival2; pi = pi2; // pi now points to ival2 int &ri = ival, &ri2 = ival2; ri = ri2; // assigns ival2 to ival 22

12 Pointers to Pointers Pointers are themselves objects in memory int ival = 1024; int *pi = &ival; // pi points to an int int **ppi = π // ppi points to a pointer to int 23 Pointers - Access Array Elements when we use the name of an array in an expression, that name is automatically converted into a pointer to the first element of the array int ia[] = {0,2,4,6,8}; int *ip = ia; // ip points to ia[0] ip = &ia[4]; // ip points to last element in ia 24

13 Pointers Arithmetic int ia[] = {0,2,4,6,8}; ip = ia; // ok: ip points to ia[0] int *ip2 = ip + 4; // ok: ip2 points to ia[4] // error: ia has only 4 elements, // ia + 10 is an invalid address int *ip3 = ia + 10; // ok: distance between the pointers // ptrdiff_t is a signed integral type // in the cstddef header ptrdiff_t n = ip2 - ip; 25 Subscripts and Pointers When we subscript an array, we are really subscripting a pointer to an element in that array. int ia[] = {0,2,4,6,8}; int i = ia[0]; // ia points to the first element in ia int *p = &ia[2]; // ok: p points to ia[2] int j = p[1]; // ok: p[1] is *(p + 1) // p[1] is the same element as ia[3] int k = p[-2]; // ok: p[-2] is ia[0] 26

14 Computing an Off-the-End Pointer It is legal to compute an address one past the end of an array or object. It is not legal to dereference a pointer that holds such an address. const size_t arr_size = 5; int arr[arr_size] = {1,2,3,4,5}; int *p = arr; // ok: p points to arr[0] int *p2 = p + arr_size; // ok: p2 points // one past the end of arr // caution- do not dereference 27 Pointers - Accessing Elements of Array const size_t arr_sz = 5; int int_arr[arr_sz] = { 0, 1, 2, 3, 4 }; // pbegin points to first element, // pend points just after the last for (int *pbegin = int_arr, *pend = int_arr + arr_sz; pbegin!= pend; ++pbegin) // print the current element cout << *pbegin << ' '; 28

15 Pointers to const Object const double pi = 3.14; double *ptr = π // error: ptr is a plain pointer const double *cptr = π // ok: cptr is a pointer to const const int universe = 42; const void *cpv = &universe; // ok: cpv is const void *pv = &universe; // error: universe is const double dval = 3.14; cptr = &dval; // ok: but can't change dval through cptr 29 const Pointer int errnumb = 0; int *const curerr = &errnumb; //curerr is a constant pointer curerr = curerr; // error: curerr is const // a pointer is itself const says nothing about // whether we can use the pointer to change the value // to which it points if (*curerr) { errorhandler(); *curerr = 0; // ok } const double pi = ; // pi_ptr is const and points to a const object // neither the value of the object addressed by pi_ptr // nor the address itself can be changed const double *const pi_ptr = π 30

16 C-Stype Character Strings char ca1[] = {'C', '+', '+'}; // no null, not C-style string char ca2[] = {'C', '+', '+', '\0'}; // explicit null char ca3[] = "C++"; // null terminator added automatically const char *cp = "C++"; // null added automatically char *cp1 = ca1; // points to first element of a array, // but not C-style string char *cp2 = ca2; // points to first element of a //null-terminated char array C-style strings are a surprisingly rich source of bugs and are the root cause of many security problems. 31 C Library String Functions - strlen Include C header file #include <cstring> No checking on string parameters strlen(s) Returns the length of s, not counting the null. char *cstylestring = C Style String ; char nonull[] = {'C', '+', '+'}; cout << strlen(cstylestring) << endl; //? cout << strlen(nonull) << endl; //? 32

17 C Library String Functions - strcmp strcmp(s1, s2) Compares s1 and s2 for equality. Returns 0 if s1 == s2, positive value if s1 > s2, negative value if s1 < s2. const char *cp1 = "A string example"; const char *cp2 = "A different string"; int i = strcmp(cp1, cp2); // i is? i = strcmp(cp2, cp1); // i is? i = strcmp(cp1, cp1); // i is? 33 C Library String Functions strcpy & strcat strcat(s1, s2) Appends s2 to s1. Returns s1. strcpy(s1, s2) Copies s2 into s1. Returns s1. // What happens if s1 is not large enough const char *cp1 = "A string example"; // strlen = 16 const char *cp2 = "A different string"; // strlen = 18 char largestr[ ];// what if + 2 is removed strcpy(largestr, cp1); // copies cp1 into largestr strcat(largestr, " "); // adds a space strcat(largestr, cp2); // concatenates cp2 // prints A string example A different string cout << largestr << endl; 34

18 C Library String Functions strn functions strn functions force you to count still needs to count right strncat(s1, s2,n) Appends n characters from s2 onto s1. Returns s1. strncpy(s1, s2, n) Copies n characters from s2 into s1. Returns s1. char largestr[ ]; strncpy(largestr, cp1, 17); // includes the null strncat(largestr, " ", 2); strncat(largestr, cp2, 19); // adds at most 18 char, // plus a null 35 Dynamically Allocating Arrays Defining array type variable (e.g. int iarray[10];): Size if fixed Size known at compile time Exists only until end of block Heap is a pool of memory for dynamically allocated objects C programs: malloc, free C++ programs: new, delete 36

19 Static Memory Allocation 37 Dynamic Memory Allocation 38

20 Memory Layout 39 Initializing and Freeing Dynamically Allocated Array Unintialized string *psa = new string[10]; int *pia = new int[10]; Value initialized int *pia2 = new int[10] (); Elements cannot be initialized to separate values Freeing dynamic memory delete [] pia; 40

21 Operator new int *pia = new int[10]; pia[3] = 999; Heap pia Operator delete delete [] pia; pia = 0; // Best Practice Heap pia

22 Example 43 Memory Leak 44

23 Mixing C++ string and C Style String Interfacing older code string str("hello World"); char *cstr = str; // error: different type const char *cstr = str.c_str(); // ok c_str is not guaranteed to be valid indefinitely; any subsequent use of str that might change the value of str can invalidate the array. 45 Using an Array to Initialize a Vector const size_t arr_size = 6; int int_arr[arr_size] = {0, 1, 2, 3, 4, 5}; // ivec has 6 elements: each a copy of // the corresponding element in int_arr vector<int> ivec(int_arr, int_arr + arr_size); 46

24 Multidimensioned Array an array of arrays // array of size 2, // each element is an array of ints of size 3 int a[2][3]; 47 2-D Array Example 48

25 Initializing Multidimensioned Array int ia[3][4] = { }; {0, 1, 2, 3}, /* row indexed by 0 */ {4, 5, 6, 7}, /* row indexed by 1 */ {8, 9, 10, 11} /* row indexed by 2 */ int ia[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; // explicitly initialize only element 0 in each row int ia[3][4] = {{ 0 }, { 4 }, { 8 } }; // explicitly initialize row 0 int ia[3][4] = {0, 3, 6, 9}; 49 Subscripting Multidimensioned Array const size_t rowsize = 3; const size_t colsize = 4; int ia [rowsize][colsize]; // 12 uninitialized elements // for each row for (size_t i = 0; i!= rowsize; ++i) // for each column within the row for (size_t j = 0; j!= colsize; ++j) // initialize to its positional index ia[i][j] = i * colsize + j; 50

26 Pointers and Multidimensioned Array when we use the name of a multidimensioned array, it is automatically converted to a pointer to the first element in the array int ia[3][4]; int (*ip)[4] = ia; // ip points to row 0 of ia ip = &ia[2]; // ip points to row 2 of ia int *ip[4]; // array of pointers to int int (*ip)[4]; // pointer to an array of 4 ints 51

5 Arrays and Pointers

5 Arrays and Pointers 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists Lecture 11 Doubly Linked Lists & Array of Linked Lists In this lecture Doubly linked lists Array of Linked Lists Creating an Array of Linked Lists Representing a Sparse Matrix Defining a Node for a Sparse

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example Announcements Memory management Assignment 2 posted, due Friday Do two of the three problems Assignment 1 graded see grades on CMS Lecture 7 CS 113 Spring 2008 2 Safe user input If you use scanf(), include

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009 Software Engineering Concepts: Testing Simple Class Example continued Pointers & Dynamic Allocation CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009 Glenn G. Chappell Department

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

Fondamenti di C++ - Cay Horstmann 1

Fondamenti di C++ - Cay Horstmann 1 Fondamenti di C++ - Cay Horstmann 1 Review Exercises R10.1 Line 2: Can't assign int to int* Line 4: Can't assign Employee* to Employee Line 6: Can't apply -> to object Line 7: Can't delete object Line

More information

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure Short Notes on Dynamic Memory Allocation, Pointer and Data Structure 1 Dynamic Memory Allocation in C/C++ Motivation /* a[100] vs. *b or *c */ Func(int array_size) double k, a[100], *b, *c; b = (double

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

C Strings and Pointers

C Strings and Pointers Motivation The C++ string class makes it easy to create and manipulate string data, and is a good thing to learn when rst starting to program in C++ because it allows you to work with string data without

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

Chapter 13 Storage classes

Chapter 13 Storage classes Chapter 13 Storage classes 1. Storage classes 2. Storage Class auto 3. Storage Class extern 4. Storage Class static 5. Storage Class register 6. Global and Local Variables 7. Nested Blocks with the Same

More information

Lecture 2. Binary and Hexadecimal Numbers

Lecture 2. Binary and Hexadecimal Numbers Lecture 2 Binary and Hexadecimal Numbers Purpose: Review binary and hexadecimal number representations Convert directly from one base to another base Review addition and subtraction in binary representations

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine 7 Objectives After completing this lab you will: know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine Introduction Branches and jumps provide ways to change

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00 MPLAB TM C30 Managed PSV Pointers Beta support included with MPLAB C30 V3.00 Contents 1 Overview 2 1.1 Why Beta?.............................. 2 1.2 Other Sources of Reference..................... 2 2

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Data Structures using OOP C++ Lecture 1

Data Structures using OOP C++ Lecture 1 References: 1. E Balagurusamy, Object Oriented Programming with C++, 4 th edition, McGraw-Hill 2008. 2. Robert Lafore, Object-Oriented Programming in C++, 4 th edition, 2002, SAMS publishing. 3. Robert

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

Binary storage of graphs and related data

Binary storage of graphs and related data EÖTVÖS LORÁND UNIVERSITY Faculty of Informatics Department of Algorithms and their Applications Binary storage of graphs and related data BSc thesis Author: Frantisek Csajka full-time student Informatics

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

C++ Support for Abstract Data Types

C++ Support for Abstract Data Types Topics C++ Support for Abstract Data Types Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.cs.wustl.edu/schmidt/ (615) 343-8197 Describing Objects Using ADTs Built-in vs.

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

8.5. <summary>...26 9. Cppcheck addons...27 9.1. Using Cppcheck addons...27 9.1.1. Where to find some Cppcheck addons...27 9.2.

8.5. <summary>...26 9. Cppcheck addons...27 9.1. Using Cppcheck addons...27 9.1.1. Where to find some Cppcheck addons...27 9.2. Cppcheck 1.72 Cppcheck 1.72 Table of Contents 1. Introduction...1 2. Getting started...2 2.1. First test...2 2.2. Checking all files in a folder...2 2.3. Excluding a file or folder from checking...2 2.4.

More information

Functions and Parameter Passing

Functions and Parameter Passing Chapter 5: Functions and Parameter Passing In this chapter, we examine the difference between function calls in C and C++ and the resulting difference in the way functions are defined in the two languages.

More information

Static Code Analysis Procedures in the Development Cycle

Static Code Analysis Procedures in the Development Cycle Static Code Analysis Procedures in the Development Cycle Tools, Technology, and Process in Engineering at Microsoft Mooly Beeri Microsoft Haifa R&D Center Agenda Static code analysis tools PREfix and PREfast

More information

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. 1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated

More information

Stack Allocation. Run-Time Data Structures. Static Structures

Stack Allocation. Run-Time Data Structures. Static Structures Run-Time Data Structures Stack Allocation Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers,

More information

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum James P. Kelsh James.Kelsh@cmich.edu Roger Y. Lee lee@cps.cmich.edu Department of Computer Science Central

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

Arrays in Java. Working with Arrays

Arrays in Java. Working with Arrays Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

More information

Cours de C++ Utilisations des conteneurs

Cours de C++ Utilisations des conteneurs Cours de C++ Utilisations des conteneurs Cécile Braunstein cecile.braunstein@lip6.fr 1 / 18 Introduction Containers - Why? Help to solve messy problems Provide useful function and data structure Consistency

More information

public static void main(string[] args) { System.out.println("hello, world"); } }

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

Conversion Constructors

Conversion Constructors CS106L Winter 2007-2008 Handout #18 Wednesday, February 27 Conversion Constructors Introduction When designing classes, you might find that certain data types can logically be converted into objects of

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

Coding conventions and C++-style

Coding conventions and C++-style Chapter 1 Coding conventions and C++-style This document provides an overview of the general coding conventions that are used throughout oomph-lib. Knowledge of these conventions will greatly facilitate

More information

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector { Software Design (C++) 3. Resource management and exception safety (idioms and technicalities) Juha Vihavainen University of Helsinki Preview More on error handling and exceptions checking array indices

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand the pass-by-value and passby-reference argument passing mechanisms of C++ Understand the use of C++ arrays Understand how arrays are passed to C++ functions Call-by-value

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint) TN203 Porting a Program to Dynamic C Introduction Dynamic C has a number of improvements and differences compared to many other C compiler systems. This application note gives instructions and suggestions

More information

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6) Semantic Analysis Scoping (Readings 7.1,7.4,7.6) Static Dynamic Parameter passing methods (7.5) Building symbol tables (7.6) How to use them to find multiply-declared and undeclared variables Type checking

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Real Application Design Christian Nastasi http://retis.sssup.it/~lipari http://retis.sssup.it/~chris/cpp Scuola Superiore Sant Anna Pisa April 25, 2012 C. Nastasi (Scuola

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

Industrial Programming

Industrial Programming Industrial Programming Systems Programming & Scripting Lecture 11: Systems Programming in C# Industrial Programming 1 Characteristics of System Programming in C# Build algorithms and data structures from

More information

CS106A, Stanford Handout #38. Strings and Chars

CS106A, Stanford Handout #38. Strings and Chars CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes

More information

Fast Arithmetic Coding (FastAC) Implementations

Fast Arithmetic Coding (FastAC) Implementations Fast Arithmetic Coding (FastAC) Implementations Amir Said 1 Introduction This document describes our fast implementations of arithmetic coding, which achieve optimal compression and higher throughput by

More information

Adding Alignment Support to the C++ Programming Language / Wording

Adding Alignment Support to the C++ Programming Language / Wording Doc No: SC22/WG21/N2341 J16/07-0201 of project JTC1.22.32 Date: 2007-07-18 Phone: +358 40 507 8729 (mobile) +1-503-712-8433 Reply to: Attila (Farkas) Fehér Clark Nelson Email: attila f feher at ericsson

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

N3458: Simple Database Integration in C++11

N3458: Simple Database Integration in C++11 N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München neumann@in.tum.de 2012-10-22 Many applications make use of relational database to store and query their data. However,

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

C PROGRAMMING FOR MATHEMATICAL COMPUTING

C PROGRAMMING FOR MATHEMATICAL COMPUTING UNIVERSITY OF CALICUT SCHOOL OF DISTANCE EDUCATION BSc MATHEMATICS (2011 Admission Onwards) VI Semester Elective Course C PROGRAMMING FOR MATHEMATICAL COMPUTING QUESTION BANK Multiple Choice Questions

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

More information

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman

More information

MISRA-C:2012 Standards Model Summary for C / C++

MISRA-C:2012 Standards Model Summary for C / C++ MISRA-C:2012 Standards Model Summary for C / C++ The LDRA tool suite is developed and certified to BS EN ISO 9001:2000. This information is applicable to version 9.4.2 of the LDRA tool suite. It is correct

More information

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer. Coding Rules Section A: Linux kernel style based coding for C programs Coding style for C is based on Linux Kernel coding style. The following excerpts in this section are mostly taken as is from articles

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

Simple C Programs. Goals for this Lecture. Help you learn about:

Simple C Programs. Goals for this Lecture. Help you learn about: Simple C Programs 1 Goals for this Lecture Help you learn about: Simple C programs Program structure Defining symbolic constants Detecting and reporting failure Functionality of the gcc command Preprocessor,

More information

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function More C++ Concepts Operator overloading Friend Function This Operator Inline Function 1 Review There are different types of member functions in the definition of a class Accessor int Str :: get_length();

More information

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following: In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our

More information

Basics of C++ and object orientation in OpenFOAM

Basics of C++ and object orientation in OpenFOAM Basics of C++ and object orientation in OpenFOAM To begin with: The aim of this part of the course is not to teach all of C++, but to give a short introduction that is useful when trying to understand

More information

Programming languages C

Programming languages C INTERNATIONAL STANDARD ISO/IEC 9899:1999 TECHNICAL CORRIGENDUM 2 Published 2004-11-15 INTERNATIONAL ORGANIZATION FOR STANDARDIZATION МЕЖДУНАРОДНАЯ ОРГАНИЗАЦИЯ ПО СТАНДАРТИЗАЦИИ ORGANISATION INTERNATIONALE

More information

NDK: NOVELL NSS AUDIT

NDK: NOVELL NSS AUDIT www.novell.com/documentation NDK: NOVELL NSS AUDIT Developer Kit August 2015 Legal Notices Novell, Inc., makes no representations or warranties with respect to the contents or use of this documentation,

More information

Applied Informatics C++ Coding Style Guide

Applied Informatics C++ Coding Style Guide C++ Coding Style Guide Rules and Recommendations Version 1.4 Purpose of This Document This document describes the C++ coding style employed by Applied Informatics. The document is targeted at developers

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

For the next three questions, consider the class declaration: Member function implementations put inline to save space. Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:

More information

Symbol Tables. Introduction

Symbol Tables. Introduction Symbol Tables Introduction A compiler needs to collect and use information about the names appearing in the source program. This information is entered into a data structure called a symbol table. The

More information

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third

More information

GDB Tutorial. A Walkthrough with Examples. CMSC 212 - Spring 2009. Last modified March 22, 2009. GDB Tutorial

GDB Tutorial. A Walkthrough with Examples. CMSC 212 - Spring 2009. Last modified March 22, 2009. GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 What is gdb? GNU Debugger A debugger for several languages, including C and C++ It allows you to inspect what the program

More information

No no-argument constructor. No default constructor found

No no-argument constructor. No default constructor found Every software developer deals with bugs. The really tough bugs aren t detected by the compiler. Nasty bugs manifest themselves only when executed at runtime. Here is a list of the top ten difficult and

More information

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Dr. Martin O. Steinhauser University of Basel Graduate Lecture Spring Semester 2014 Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Friday, 7 th March

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

EXEC SQL CONNECT :userid IDENTIFIED BY :passwd;

EXEC SQL CONNECT :userid IDENTIFIED BY :passwd; SQL with C Test Program 1: Select a row with one column int value; EXEC SQL select max (b) into :value from r; printf ("connected\n"); printf ("max (b) = %d\n", value); Ensure that your library path is

More information