PIC 10A Pointers, Arrays, and Dynamic Memory Allocation
|
|
- Dustin Webster
- 7 years ago
- Views:
Transcription
1 PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Last edited: February 10, 2017
2 Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable. double d = 0.1 ; double * d_p = &d; cout << d_p << endl ; The output happens to be 008FF780. 2
3 Pointers double * d_p ; d_p is a variable of type double* (read as double pointer ). Or we say d_p a pointer to a double. double * d_p = &d; &d returns the address of d, and it is of type double*. cout << d_p << endl ; This outputs the memory address at which d is stored. A double is 8 bytes. So the memory addresses 008FF780, 008FF781,..., 008FF787 are used to store d. 3
4 Pointers The indirection or dereference operator * allows us to access the variable a pointer is pointing to. double d = 0.1 ; double * d_p = &d; cout << * d_p << endl ; * d_p = 3.0 ; cout << d << endl ; The output is 0.1 and 3.0. *d_p returns the double of value 0.1. *d_p = 3.0; assigns 3.0 to the double at location d_p. You now know 3 separate uses for the symbol *: multiplication, dereferencing, and defining a pointer. 4
5 sizeof operator The sizeof operator returns the number of bytes it take to store a variable cout << sizeof ( int ) << endl ; cout << sizeof ( double ) << endl ; The output (on my machine) is 4 and 8. 5
6 Arrays An array is a sequence of variables. int ages [10 ]; for ( int i=1; i <= 10; i ++) { int thisage ; cout << " Student number " << i <<" has age : "; cin >> thisage ; ages [i-1] = thisage ; //0- based indexnig } cout << " The ages are " << endl ; for ( int i=0; i<10; i ++) cout << ages [i] << endl ; (Elements of an array is accessed with 0-based indexing.) 6
7 Arrays are pointers Actually arrays are (almost) pointers! int ages [10 ]; int * int_ p = ages ; // ages is of type int * for ( int i=1; i <= 10; i ++) {... // Initialize ages [ ] } cout << ages << endl ; cout << int_ p << endl ; for ( int i=0; i<10; i ++) cout << int_ p [ i] << endl ; // You can do this int_p and ages are the same. 7
8 Arrays are pointers Since ages is of type int*, it points to a memory address at which an integer is stored. int ages [10 ]; for ( int i=1; i <= 10; i ++) {... // Initialize ages [ ] } cout << ages << endl ; The output is the address of ages[0]. 8
9 The memory layout of an array 9
10 Pointer arithmetic You can do basic arithmetic with pointers. Since sizeof(int) is 4, int_p+1 points to the address 4 bytes away from int_p cout << int_ p << endl ; cout << ( int_p +1) << endl ; The output happens to be 00F3FC64 and 00F3FC68. 10
11 Arrays are pointers We can also access an array with pointer arithmetic (as opposed to using []). for ( int i=0; i<10; i ++) cout << ages [i] << endl ; for ( int i=0; i<10; i ++) cout << *( ages + i) << endl ; for ( int * iter = ages ; iter <( ages +10 ); iter ++) cout << * iter << endl ; These 3 for loops have the same output. 11
12 Array initialization We can declare and initialize a variable in one statement using an initializer list. double d = 0.3 ; We can do the same with arrays. // w has length 3 and holds 1,2,3 int w[] = {1,2,3}; // x has length 5 and holds 1,2,3000,0,0 float x[5] = {1.f,2.f,3 E3f }; // y has length 3 and holds all zeroes int y[3] = {0}; // Better style? // z has length 10 and holds all zeroes double z[10] = {}; 12
13 Where do variables go? The pointers reveal the physical location of the variables. Where do they go? The operating system (OS) keeps track of which patch of memory is available. When the C++ program declares a variable, it asks the OS for memory. Which patch of memory you get depends on what part of the memory is available, which in turns depends on the what other programs are running and the current state of the OS. Arrays are placed on a contiguous patch of memory. This has to be true for pointer arithmetic to work. 13
14 (const) pointer to a (const) variable A pointer can change which variable it points to and, when dereferenced with *, change the variable it points to. double d1 = 0.3 ; double d2 = 0.1 ; double * d_p ; d_p = &d1; d_p = &d2; * d_p += 5.; 14
15 (const) pointer to a (const) variable A const pointer to a double can change the double it points to but not which double it points to. double d1 = 0.3 ; double d2 = 0.1 ; double * const d_p = & d1; * d_p += 5.; d_p = &d2; // Error! Read double* const as a const pointer to a double. 15
16 (const) pointer to a (const) variable A pointer to a const double can change which double it points to but not the double it points to double d1 = 0.3 ; double d2 = 0.1 ; const double * d_p = & d1; d_p = &d2; * d_p += 5.; // Error! Read const double* as a pointer to a const double. 16
17 (const) pointer to a (const) variable A const pointer to a const double can change neither which double it points to nor the double it points to double d1 = 0.3 ; double d2 = 0.1 ; const double * const d_p = & d1; d_p = &d2; // Error! * d_p += 5.; // Error! Read const double* const as a const pointer to a const double. 17
18 const and pointer syntax As if this wasn t already a mess, the lax syntax rules for writing const and pointers exacerbate the problem. const type and type const are the same. const double d1 = 0.3 ; double const d2 = 0.1 ; // bad style Both are valid. Whitepsace around * has no affect. double * d_p1 ; // bad style double * d_p2 ; double * d_ p3 ; double * d_p4 ; All are valid. 18
19 const and pointer syntax Really, * belongs to the variable, not the the type. double * d_p1, d_ p2 ; // d_ p2 is not a pointer double * d_p3, * d_ p4 ; // both are pointers A C programmer would say double *d_p means *d_p is a double. To a C++ programmer double* d_p makes more sense; d_p is a variable with certain type. The correct syntax for declaring multiple pointers in one statement makes no sense. So don t use it. double * d_p1, * d_p2 ; // bad style, unclear double * d_p3 ; // good style double * d_p4 ; // good style 19
20 const and pointer syntax const after * signifies the pointer is const. double d; double * const d_p1 = &d, * d_p2 = &d; double * const d_p3 = &d, * const d_p4 = &d; d_p2 ++; // bad style // Only d_ p2 is not const You can mix and match (but you shouldn t). const double * const d_ p1 = & d; const double * const d_ p2 = & d; // best style const double * const d_ p3 = & d; double const * const d_ p4 = & d; double const * const d_ p5 = & d; double const * const d_ p6 = & d; double const * const d_p7 = &d; Use whitespace to make the correct emphasis. 20
21 const and pointer syntax Tip #1: Read backwards: const double * const d_p = & d; Read constant pointer to (const double). Tip #2: Split the statement at *. const on the left is on the original type, and const on the right is on the pointer. 21
22 Type conversion Type conversion or type casting is the conversion of a variable of one type to another. double d1 = 3; 3 is a literal of type int, and it is (implicitly) converted/casted into a double. There are explicit and implicit conversions. 22
23 Type conversion: explicit Explicitly converting from type T1 to T2. C-style cast: (T2) T1. float f = ( float ) 3; // cast int to float double d = ( double ) f; // cast float to double // cast 1 and 3 into double before division cout << (( double ) 1) / (( double ) 3) << endl ; Functional cast or function style cast: T2(T1). int i = ; // i = 2 billion cout << 10 * i << endl ; cout << 10 *( long long int ( i) ) << endl ; The output is and
24 Type conversion: explicit Explicitly converting from type T1 to T2. Static cast: static_cast<t2>(t1). bool b1 = static_cast <bool >(0); bool b2 = static_cast <bool >(3); cout << b1 << endl ; cout << b2 << endl ; The output is 0 and 1. We will later discuss where the names C-style cast and functional cast come from. Upon encountering these casts, the compiler will attempt to carry them out. If there is no a suitable way, the cast will fail (i.e., your code won t compile). int i = 3; string s1 = static_cast < string >(i); // Error! We ll later learn what a suitable way of conversion means. 24
25 Type conversion: implicit Implicit conversion from type T1 to type T2 is attempted when type T1 is used where type T2 is expected. double d = 5; // Implicit cast from int to double int i = 3; float f = i; // Implicit cast from int to float Non-const pointers can be implicitly converted to const pointers. Conversion from const to non-const pointers doesn t happen. double d1; double * d_p1 ; const double d2 = 0.1 ; const double * d_ p2 ; d_p1 = &d1; d_ p2 = & d1; // convert double * to const double * d_p1 = dp_2 ; // Error d_p1 = &d2; // Error 25
26 Type conversion: which one? Which cast should you use? Ordered in verbosity: static < functional = C-style < implicit. Ordered in readability (subjective): funcational > static > implicit > C-style. Ordered in safety: static > functional = C-style > implicit. Static cast is safe because it is conspicuous in that is is more visible and in that you can easily search (with ctrl+f) to find it. (There s one more subtle reason that s beyond the scope of this class.) In my opinion, the functional cast is always better than the C-style cast. Otherwise, handle the trade-off on a case-by-case basis. 26
27 typeid Use typeid to check what type your object is. # include < iostream > # include < typeinfo > using namespace std ; int main () { int i=5; long long int j = 2; cout << typeid ( i). name () << endl << typeid (j). name () << endl << typeid (i+j). name () << endl ; } Output is int, int64, and int64. 27
28 The type char The type char (short for character) is a fundamental type. sizeof(char) equals 1. A literal of type char is written as a single character in single quotes. char c1 = a ; cout << c1 << endl ; 28
29 The type char A char can take on 256 possible values. (Why 256?) The ASCII standard (American Standard Code for Information Interchange) specifies which value corresponds to which character. # include < iostream > # include < bitset > using namespace std ; int main () { char c = char (65 ); cout << c << endl ; bitset <8> x(c); cout << x << endl ; // see the bits stored in & c } The output is A and
30 Arithmetic with char We also can view char as an integer type with a value range of 128 to 127. You can (implicitly) cast a char into an int and perform arithmetic. char c; while ( true ) { cout << " Enter a lower case letter " << endl ; cin >> c; cout << "We capitalized it: " << char (c-0 x20 ) << endl ; cout << typeid. name (c-0 x20 ) << endl ; // int } 0x20 is a literal of type int written in hex. 0x or 0X means hex. In c-0x20, we have a char minus an int. So c, a char, is implicitly converted into an int to perform the arithmetic. char(c-0x20) converts the int back to a char. 30
31 Relational operators with char The comparison operators are quite useful. char c; cout << " Input a letter " << endl ; cin >> c; if ( a <=c && c <= z ) cout << " Input is lower case " << endl ; else if ( A <=c && c <= Z ) cout << " Input is upper case " << endl ; else if ( 0 <=c && c <= 9 ) cout << " Input is a number " << endl ; else if ( <= c && c <= ~ ) cout << " Input is a special character " << endl ; else cout << " Input is something else " << endl ; 31
32 char array A char array is more than just a sequence of chars. In programming, a string is a sequence of characters. In C++ there are 2 common ways to represent a string: with type string and with a char array. A C-style string is a char array terminated by the null character, written as \0 or char(0). strings are better than C-style strings, but you must know both. 32
33 char array initialization char arrays are special in that they have an additional way to initialize. char s1 [] = { H, e, l, l, o, \0 }; char s2 [] = " Hello "; // special syntax char s3 [] = { H, e, l, l, o }; s1 and s2, valid c-strings, are char arrays of size 6. s3, not a valid c-string, is of size 5. 33
34 char array initialization The normal initializer list syntax works with char arrays. char s1[5] = { a, b }; char s2[5] = { a, b, \0, \0, \0 }; cout << int (s1[2]) << endl ; The output is 0. s1 and s2 are the same valid C-style strings. 34
35 cout treats char arrays specially. char array cout int i_a [] = {1,2,3}; char s1 [] = { H, e, l, l, o, \0 }; char s2 [] = " Hello "; // special syntax char s3 [] = { H, e, l, l, o }; cout << i_a << endl ; // pointer address cout << s1 << endl ; // Hello cout << s2 << endl ; // Hello cout << s3 << endl ; // Fail Instead of printing the address s1, cout performs something like for ( int i=0; s1[i ]!= \0 ; i ++) cout << s1[i]; cout << endl ; So cout needs the terminating null character to know when to stop. 35
36 C-string literals "Hello" isn t a literal of type string. It s actually a literal of type const char *. cout << typeid (" Hello "). name () << endl ; const char * s = " Hello "; cout << s << endl ; When we assign a C-string literal to a string, implicit type casting happens. // string s = " Hello world "; // the same as string s = static_ cast < string >(" Hello world "); 36
37 char array syntactic sugar An astute attention to detail reveals that the special syntax for initializing a character array must be syntactic sugar, as it makes no syntactic sense. const char * s1 = " Hello "; // not sugar cout << typeid (" test "). name () << endl ; char s2 [] = " Hello "; // sugar char s3 [] = s1; // Error char s4 [] = s2; // Error Normally, you shouldn t be able to assign const char * (a memory address) into a char array. 37
38 Limitations of arrays (on the stack) The length of the array must be a constant (i.e., specified in the code). int n; cin >> n; double d[n]; // Error Using const int doesn t solve the problem. int n; cin >> n; const int m = n; double d[m]; // Error These arrays can t be too large. int arr [ ]; // Error 1,000,000 ints occupy merely 4 megabytes. 38
39 Stack vs. heap Within memory, there is the stack and the heap. The stack is small but fast (for reasons beyond the scope of this class). The variable and array definitions we ve seen so far place the variables on the stack. These are also called local or automatic variables. The heap, also called dynamic memory, is large but slower (but still fast compared to secondary storage). We will learn dynamic memory allocation, which places variables on the heap. In C++, the opposite of dynamic variables isn t static variables. Static variables mean something else unrelated to the stack. 39
40 Dynamic allocation Use the new operator to declare a variable on the heap. double * d_ p1 = new double ; new T creates a variable of type T and returns a pointer pointing to it. Variables on the stack don t use new. double b = 0.0 ; 40
41 delete operator You must deallocate a dynamically allocated variable with the delete operator when you re done with it. In other words, you must free the memory when you re done with it. double * d_p = new double ;... // code using d_p ; delete d_p ; The deallocation tells the OS that we re no longer using the memory address. Variables on the stack are deallocated automatically when they go out of scope. 41
42 delete operator int main () { { double d = 0.1 ; double * d_p = new double ; * d_p = d; // delete d_p ; } delete d_p ; // error } d and d_p are automatically deallocated but *d_p is not. Since d_p is gone, we lost the address of *d_p, and there s no way to deallocate *d_p. 42
43 Dynamic arrays Use new T[n] to declare an array of type T of length n on the heap. int n; cin >> n; double * d_a = new double [ n]; delete [] d_a ; You must use delete[] to deallocate a dynamic array. Don t use delete[x]. Don t use delete. Use delete[]. 43
44 Dynamic arrays Advantages of dynamic arrays over local arrays: Array length does not have to be predetermined. Array can be large enough to hold gigabytes. # include < iostream > using namespace std ; int main () { int n; cin >> n; char * c_a = new char [n]; cout << " wait a second "; char c; cin >> c; // check the memory monitor delete [] c_a ; cout << " memory has been freed "; cin >> c; } 44
45 Memory leak When you don t free memory you allocate, the memory is leaked and becomes unavailable until the end of the program. (The OS reclaims the memory when the program is done.) int main () { int count = 0; while ( true ) { char * c_p ; c_p = new char [ ]; count ++; cout << count << " Mbytes of memory leaked.\ n"; } } Memory leaks are one of the worst kinds of bugs! They are very hard to track down as they often do no immediate harm. However, they can lead your program to run out of memory and crash over time. 45
46 Arrays vs. pointers Actually, there is a small difference between an array and a pointer. Write T [] for an array of type T. int main () { int * n; int m[2]; int * k = new int [10 ]; cout << typeid (n). name () << \n ; cout << typeid (m). name () << \n ; cout << typeid (k). name () << \n ; delete [] k; } The distinction is rarely necessary. Only local arrays can have type T []. 46
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 informationMemory 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 informationComp151. 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 informationC++ 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 informationSources: 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 informationThe programming language C. sws1 1
The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan
More informationBoolean 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 informationLecture 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 informationThe 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 informationChapter 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 informationStorage 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 informationSimple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language
Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from
More informationCS 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 informationSemantic 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 informationPassing 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 informationFirst Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
More informationAn 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 informationObject-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 informationMember Functions of the istream Class
Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,
More informationMemory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation
Dynamic Storage Allocation CS 44 Operating Systems Fall 5 Presented By Vibha Prasad Memory Allocation Static Allocation (fixed in size) Sometimes we create data structures that are fixed and don t need
More informationBase Conversion written by Cathy Saxton
Base Conversion written by Cathy Saxton 1. Base 10 In base 10, the digits, from right to left, specify the 1 s, 10 s, 100 s, 1000 s, etc. These are powers of 10 (10 x ): 10 0 = 1, 10 1 = 10, 10 2 = 100,
More informationIntroduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
More informationOrganization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.
Organization of Programming Languages CS320/520N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Names, Bindings, and Scopes A name is a symbolic identifier used
More informationarrays 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 informationASCII 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 informationC++ 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 informationChapter 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 informationBasics 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 informationJava 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 informationProgramming Project 1: Lexical Analyzer (Scanner)
CS 331 Compilers Fall 2015 Programming Project 1: Lexical Analyzer (Scanner) Prof. Szajda Due Tuesday, September 15, 11:59:59 pm 1 Overview of the Programming Project Programming projects I IV will direct
More informationLecture 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 informationAnswers 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 informationObject 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 informationMoving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
More informationC++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 informationIntroduction to Data Structures
Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate
More informationIntroduction to Python
WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language
More informationHow To Write Portable Programs In C
Writing Portable Programs COS 217 1 Goals of Today s Class Writing portable programs in C Sources of heterogeneity Data types, evaluation order, byte order, char set, Reading period and final exam Important
More informationShort 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 informationAppendix K Introduction to Microsoft Visual C++ 6.0
Appendix K Introduction to Microsoft Visual C++ 6.0 This appendix serves as a quick reference for performing the following operations using the Microsoft Visual C++ integrated development environment (IDE):
More informationFunctions 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 informationWe will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
More informationNumber Representation
Number Representation CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Topics to be Discussed How are numeric data
More informationLab 4.4 Secret Messages: Indexing, Arrays, and Iteration
Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration This JavaScript lab (the last of the series) focuses on indexing, arrays, and iteration, but it also provides another context for practicing with
More informationLecture 22: C Programming 4 Embedded Systems
Lecture 22: C Programming 4 Embedded Systems Today s Goals Basic C programming process Variables and constants in C Pointers to access addresses Using a High Level Language High-level languages More human
More informationCpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing
CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects
More informationSymbol 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 information1 The Java Virtual Machine
1 The Java Virtual Machine About the Spec Format This document describes the Java virtual machine and the instruction set. In this introduction, each component of the machine is briefly described. This
More informationEmbedded 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 information5 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 informationUniversity of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python
Introduction Welcome to our Python sessions. University of Hull Department of Computer Science Wrestling with Python Week 01 Playing with Python Vsn. 1.0 Rob Miles 2013 Please follow the instructions carefully.
More informationCalling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?
Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function
More informationHow 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 informationIntroduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:
More informationPART-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 informationExample. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:
Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,
More informationMISRA-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 informationKeywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void
1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of
More informationScoping (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 informationCrash Course in Java
Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is
More information13 Classes & Objects with Constructors/Destructors
13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.
More informationC++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 informationProgramming Languages
Programming Languages Programming languages bridge the gap between people and machines; for that matter, they also bridge the gap among people who would like to share algorithms in a way that immediately
More informationThe University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each)
True or False (2 points each) The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002 1. Using global variables is better style than using local
More informationSequential Program Execution
Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper
More informationHandout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
More information1 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 informationQUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1
QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For
More informationThe C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures
The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops
More informationObject 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 informationInformatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)
More informationPROBLEM 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 informationThe Hexadecimal Number System and Memory Addressing
APPENDIX C The Hexadecimal Number System and Memory Addressing U nderstanding the number system and the coding system that computers use to store data and communicate with each other is fundamental to
More informationLab Experience 17. Programming Language Translation
Lab Experience 17 Programming Language Translation Objectives Gain insight into the translation process for converting one virtual machine to another See the process by which an assembler translates assembly
More informationSemester Review. CSC 301, Fall 2015
Semester Review CSC 301, Fall 2015 Programming Language Classes There are many different programming language classes, but four classes or paradigms stand out:! Imperative Languages! assignment and iteration!
More informationConditions & Boolean Expressions
Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In
More informationAn overview of FAT12
An overview of FAT12 The File Allocation Table (FAT) is a table stored on a hard disk or floppy disk that indicates the status and location of all data clusters that are on the disk. The File Allocation
More informationProgramming Languages CIS 443
Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception
More information1) 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 informationChapter 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 informationChapter 7D The Java Virtual Machine
This sub chapter discusses another architecture, that of the JVM (Java Virtual Machine). In general, a VM (Virtual Machine) is a hypothetical machine (implemented in either hardware or software) that directly
More informationPL / SQL Basics. Chapter 3
PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic
More informationClass Notes for CSCI 104: Data Structures and Object-Oriented Design
Class Notes for CSCI 104: Data Structures and Object-Oriented Design David Kempe and the awesome Fall 2013 sherpas August 12, 2016 2 Preface These lecture notes grew out of class notes provided for the
More informationBachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)
Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating
More informationMemory is implemented as an array of electronic switches
Memory Structure Memory is implemented as an array of electronic switches Each switch can be in one of two states 0 or 1, on or off, true or false, purple or gold, sitting or standing BInary digits (bits)
More informationCSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014
CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages Nicki Dell Spring 2014 What is a Programming Language? A set of symbols and associated tools that translate (if necessary) collections
More informationStack 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 informationThe little endl that couldn t
This is a pre-publication draft of the column I wrote for the November- December 1995 issue of the C++ Report. Pre-publication means this is what I sent to the Report, but it may not be exactly the same
More informationpublic 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 informationBasics 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 informationPitfalls in Embedded Software
Pitfalls in Embedded Software..and how to avoid them Sagar Behere 31 March 2014 Pitfalls in Embedded Software 1 / 19 What is wrong with this code? unsigned int count = BigValue; for (int i = 0; i < count;
More informationTopics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives
Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,
More informationCompiler Construction
Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from
More informationStacks. 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 informationOutline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions
More informationDNA Data and Program Representation. Alexandre David 1.2.05 adavid@cs.aau.dk
DNA Data and Program Representation Alexandre David 1.2.05 adavid@cs.aau.dk Introduction Very important to understand how data is represented. operations limits precision Digital logic built on 2-valued
More informationA brief introduction to C++ and Interfacing with Excel
A brief introduction to C++ and Interfacing with Excel ANDREW L. HAZEL School of Mathematics, The University of Manchester Oxford Road, Manchester, M13 9PL, UK CONTENTS 1 Contents 1 Introduction 3 1.1
More information