Dynamic arrays / C Strings

Similar documents
CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Separate compilation

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Memory, Arrays & Pointers

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

Pointers. Pointers. Pointers (cont) CS 217

CSE 303 Midterm Exam

Course organization. Course introduction ( Week 1)

CS 455 Final Exam Fall 2012 [Bono] Dec. 17, 2012

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Chapter 13. Functions and Parameter Passing (Part 2)

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Engineering Problem Solving with C++, Etter

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

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Using Objects. a first example of an object classes and objects in Java

Pointers. Pointer References

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Array Initialization

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Separate Compilation Model

2 2

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

EE 312 Fall 2017 Midterm 1 October 12, 2017

Arrays and Pointers in C. Alan L. Cox

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Pointers, Dynamic Data, and Reference Types

CS 222: Pointers and Manual Memory Management

CS 115 Exam 3, Spring 2010

PRINCIPLES OF OPERATING SYSTEMS

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

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

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:


C++ for Java Programmers

CS 61c: Great Ideas in Computer Architecture

REFERENCES, POINTERS AND STRUCTS

CSE 333 Midterm Exam 7/29/13

Arrays and Pointers. CSE 2031 Fall November 11, 2013

About this exam review

EX3 Code Review. Instructor: Tsung-Che Chiang

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

a data type is Types

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

The paramaterless ctor (aka default ctor)

More on class design

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

CA341 - Comparative Programming Languages

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

CS 455 Midterm Exam 1 Spring 2013 [Bono] Feb. 21, 2013

CSE 333 Midterm Exam 2/14/14

Lectures 5-6: Introduction to C

Strings and Stream I/O

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

ECE Fall 20l2, Second Exam


Contents. A Review of C language. Visual C Visual C++ 6.0

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

CS 455 Midterm Exam 1 Fall 2015 [Bono] Thursday, Oct. 1, 2015

Understanding Pointers

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Chapter 10 Characters, Strings, and the string class

BLM2031 Structured Programming. Zeyneb KURT

Arrays and Pointers (part 1)

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS 455 Final Exam Spring 2017 [Bono] May 10, 2017

C-String Library Functions

Fall 2018 Discussion 2: September 3, 2018

ECE 462 Fall 2011, Second Exam

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

CS 103 Lab - Party Like A Char Star

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture7 Strings and Characters

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

CE221 Programming in C++ Part 1 Introduction

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Supporting Class / C++ Lecture Notes

CSC 2400: Computer Systems. Arrays and Strings in C

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Programming Studio #9 ECE 190

CS 455 Final Exam Fall 2015 [Bono] Dec. 15, 2015

211: Computer Architecture Summer 2016

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Unit 14. Passing Arrays & C++ Strings

Arrays, Pointers and Memory Management

Introduction Slide 1/20. Introduction. Fall Semester. Parallel Computing

Common Misunderstandings from Exam 1 Material

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Transcription:

Dynamic arrays / C Strings Dynamic arrays syntax why use C strings Ex: command line arguments Call-by-pointer Dynamic Arrays / C Strings [Bono] 1

Announcements Final exam: Tue, 5/8, 8 10 am SGM 124 and OHE 132 (room assignments soon) closed book, closed note, no extra paper bring USC ID card Review session info and finals week office hours on weekby-week page soon Extra credit assignment available (due Tue 5/1) Course evals available through 5/1 via email from c-evals@usc.edu or via blackboard.usc.edu Make [Bono] 2

Class time for course evaluations Your personalized link to online course evaluations: via email you received from c-evals@usc.edu or log into blackboard.usc.edu Make [Bono] 3

Fixed vs. dynamic arrays Review: how to declare a fixed-size array of 100 int's? Can also make a dynamic array (similar to Java arrays) Dynamic Arrays / C Strings [Bono] 4

Why use dynamic arrays? Not for partially filled array applications: Easier to use STL vector do so when possible When you can't determine the array size at compile time Or if the array will need to change size during the run of the porgram. Lot s of C code uses dynamic arrays: C/C++ command-line arguments C-string is a (possibly dynamic) array of chars Dynamic Arrays / C Strings [Bono] 5

More dynamic array code // first numarr holds 10 ints // later want it to hold 20 int *numarr; Dynamic Arrays / C Strings [Bono] 6

Arrays = pointers? In C/C++ pointers and arrays are almost interchangeable. An array is a pointer whose value you can t change. Example next slide. Dynamic Arrays / C Strings [Bono] 7

Ex: Pointers vs. Arrays char a[5]; char *b = new char[5]; a[0] = x ; b[0] = y ; cout << *a; cout << *b; cout << b[0]; a = b; // illegal b = a; // legal b[1] = m ; cout << a[1]; // m Dynamic Arrays / C Strings [Bono] 8

Array parameters revisited Also, parameter types interchangeable. Can declare the following function either of these two ways: void printarray1(int *arr, int size); void printarray2(int arr[], int size); Can pass either static or dynamic array to the function: int a[10]; int *b = new int[10]; printarray1(a, 10); printarray1(b, 10); printarray2(a, 10); printarray2(b, 10); Dynamic Arrays / C Strings [Bono] 9

Ambiguous pointer type? Suppose you see the declaration: Student * s; What data structure could s be? Dynamic Arrays / C Strings [Bono] 10

Not an actual type in C C Strings C string means an array of characters but that is stored a particular way C library functions that operate on them assume that storage convention (<cstring>) Why do C++ programmers care? Dynamic Arrays / C Strings [Bono] 11

C String representation an array of characters such that, Instead of keeping numchars as separate value, it uses a sentinel to mark the end of the string. more accurate: C string is a null-terminated array of chars The sentinel used is called the null char: \0 char str[10]; strcpy(str, hello ); // copy a C string C string representation: h e l l o \0 hello is a C string literal(internally has the null char) In the following, literal C string gets converted to string object. string s = hello ; Dynamic Arrays / C Strings [Bono] 12

Dynamic C Strings Often C strings are dynamically allocated char *str; strcpy(str, hello ); // error str = new char[6]; // one extra for '\0' strcpy(str, "hello"); int len = strlen(str); // 5 char * str2 = new char[1]; strcpy(str2, ""); // empty string // or str2[0] = '\0'; Dynamic Arrays / C Strings [Bono] 13

C String library There are many C library functions for operating on C strings. Need #include <cstring> All of them have (more convenient) equivalents that work on C++ string objects Here are a few of them C string function "equiv." string operation: strcpy (doesn't alloc space) = (does alloc space) strcmp ==, <, >, etc. strlen length() (mbr func) Avoid using C strings, switch to STL string if at all possible Dynamic Arrays / C Strings [Bono] 14

How to convert a C string to a string Scenario: I have code where someone passed me a C string... Use C-string to string constructor: char *cstr;... string s(cstr); // init string with C string or string t;... t = string(cstr); // put value in existing string Note: same constructor used to init with a literal string string s("hello"); string s = "hello"; Dynamic Arrays / C Strings [Bono] 15

How to convert a string to a C string Scenario: I have to call a library function that only takes a C string (e.g., Unix library call)... There's a string method to convert to a C string: string s; //... lib_func(s.c_str()); Dynamic Arrays / C Strings [Bono] 16

Ex: command line arguments Arguments on command line are passed via parameters to main: int main(int argc, char *argv[]) argc number of arguments argv the arguments Dynamic Arrays / C Strings [Bono] 17

Ex: command line arguments (cont.) Suppose we're writing the source code for compiler. Sample call: g++ -ggdb Wall foo.cpp In main for g++ compiler: int main(int argc, char *argv[]) Values for this call: argv[0] g++ argv[1] -ggdb argv[2] -Wall argv[3] foo.cpp argc 4 Dynamic Arrays / C Strings [Bono] 18

Ex: command line arguments (cont.) You can make some assumptions: argc always >= 1 (argv[0] is program name) strlen(argv[i]) for valid i always >= 1 (non-empty strings) What to do? convert to string right away Outline of code in main to process command line args: for (int i = 1; i < argc; i++) { string arg(argv[i]); // process current arg } Code to process the current arg can use string features like length(), substr(), =, ==, [], or + Dynamic Arrays / C Strings [Bono] 19

Pass-by-pointer No call-by-reference in C But can get the effect of call by reference Pass a pointer to the object / primitive variable Calling the function: use address-of (&) In the function: dereference the pointer (*) Example Dynamic Arrays / C Strings [Bono] 20

swap using pass-by-pointer void swap(int * a, int * b) { int temp = *a; *a = *b; *b = temp; } Calling the function int x = 10; int y = 20; swap(&x, &y); Dynamic Arrays / C Strings [Bono] 21

insertfront using pass-by-pointer void insertfront(listtype * listptr, int newval) { Node * newguy = new Node(newVal); newguy->next = *listptr; *listptr = newguy; } Calling the function ListType mylist = NULL; insertfront(&mylist, 3); insertfront(&mylist, 7); Dynamic Arrays / C Strings [Bono] 22