G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Similar documents
Variables and literals

C++ for Java Programmers

PRINCIPLES OF OPERATING SYSTEMS

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Arrays and Pointers in C. Alan L. Cox

G52CPP C++ Programming Lecture 9

CS 61c: Great Ideas in Computer Architecture

Array Initialization

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

Personal SE. Functions, Arrays, Strings & Command Line Arguments

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Chapter 11 Introduction to Programming in C

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C

An overview of Java, Data types and variables

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

CSE 303: Concepts and Tools for Software Development

Intermediate Programming, Spring 2017*

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

Organization of a file

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

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

Tutorial 1 C Tutorial: Pointers, Strings, Exec

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

C-String Library Functions

ARRAYS(II Unit Part II)

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

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

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

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

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

Chapter IV Introduction to C for Java programmers

Chapter 11 Introduction to Programming in C

The University of Nottingham


The University of Nottingham

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

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

Luar Topics. C A Low level Programming Language Make A dependency based build system YUYV Representation of Color ZMP Zero Moment Point control

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

CSE 374 Programming Concepts & Tools

Programming in C. What is C?... What is C?

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Arrays, Strings, & Pointers

Chapter 11 Introduction to Programming in C

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

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

ONE DIMENSIONAL ARRAYS

Chapter 11 Introduction to Programming in C

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

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

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Final CSE 131B Spring 2005

Course organization. Course introduction ( Week 1)

Chapter 11 Introduction to Programming in C

Dynamic arrays / C Strings

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

printf( Please enter another number: ); scanf( %d, &num2);

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

Memory Corruption 101 From Primitives to Exploit

SU 2017 May 11/16 LAB 2: Character and integer literals, number systems, character arrays manipulation, relational operator

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

Lecture 04 FUNCTIONS AND ARRAYS

Strings. Steven R. Bagley

CSC 2400: Computer Systems. Arrays and Strings in C

Dynamic memory allocation

Arrays and Pointers (part 2) Be extra careful with pointers!

today cs3157-fall2002-sklar-lect05 1

Chapter 11 Introduction to Programming in C

CSC 2400: Computer Systems. Arrays and Strings in C

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

Work relative to other classes

Programming in C. 3. Pointers and Structures. Dr. Neel Krishnaswami University of Cambridge

Overview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018

CS 103 Lab - Party Like A Char Star

EMBEDDED SYSTEMS PROGRAMMING Language Basics

For instance, we can declare an array of five ints like this: int numbers[5];

Lecture 04 Introduction to pointers

Chapter 8 Character Arrays and Strings

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

C programming basics T3-1 -

High Performance Computing MPI and C-Language Seminars 2009

C-LANGUAGE CURRICULAM

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Procedural Programming & Fundamentals of Programming

CE221 Programming in C++ Part 1 Introduction

C++ basics Getting started with, and Data Types.

CS 0449 Sample Midterm

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Dynamic memory allocation (malloc)

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Computer Programming: Skills & Concepts (CP) Strings

CS 103 Lab 6 - Party Like A Char Star

Computer Programming

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Transcription:

G52CPP C++ Programming Lecture 3 Dr Jason Atkin E-Mail: jaa@cs.nott.ac.uk 1

Revision so far C/C++ designed for speed, Java for catching errors Java hides a lot of the details (so can C++) Much of C, C++ and Java are very similar char* is a pointer to a char, but can sometimes be treated as a string C++ bool values are like Java booleans ints can be used, 0 means false, non-zero (or 1) means true Sizes of C/C++ types can vary across platforms C provides a powerful library of functions You should #include the right header file to use them 2

Pointer example long l = 32; long* pl1 = &l; long* pl2 = pl1; Q: What goes into the red circled parts? Conceptually: Actually: (example addresses) pl1 l Address Name Value 1200 l 5232 pl1 pl2 6044 pl2 3

Pointer example long l = 32; long* pl1 = &l; long* pl2 = pl1; Q: What goes into the red circled parts? Conceptually: Actually: (example addresses) pl1 pl2 l 32 Address Name Value 1200 l 32 5232 pl1 6044 pl2 4

Pointer example long l = 32; long* pl1 = &l; long* pl2 = pl1; Q: What goes into the red circled parts? Conceptually: pl1 l 1200 32 pl2 Actually: (example addresses) Address Name Value 1200 l 32 5232 pl1 1200 6044 pl2 5

Pointer example long l = 32; long* pl1 = &l; long* pl2 = pl1; Assigning one pointer to another means: It points at the same object It has the same address stored in it (i.e. the same value) Conceptually: pl1 l 1200 32 Actually: (example addresses) Address Name Value 1200 l 32 5232 pl1 1200 pl2 1200 6044 pl2 1200 6

Dereferencing example long l1 = 32; long* pl1 = &l1; long* pl2 = pl1; long l2 = *pl2; What goes into the red circled parts? Hint: What is *pl2? Conceptually: pl1 l1 1200 32 pl2 l2 1200 Actually: (example addresses) Address Name Value 1200 l1 32 5232 pl1 1200 6044 pl2 1200 6134 l2 7

Dereferencing example long l1 = 32; long* pl1 = &l1; long* pl2 = pl1; long l2 = *pl2; So, we can access (use) the value of l1 without knowing it is the value of variable l1 (just the value at address pl2) Conceptually: pl1 1200 l1 32 pl2 l2 1200 32 Actually: (example addresses) Address Name Value 1200 l1 32 5232 pl1 1200 6044 pl2 1200 6134 l2 32 8

Dereferencing example long l1 = 32; long* pl1 = &l1; long* pl2 = pl1; long l2 = *pl2; *pl1 = 4; Q: What does this do? Conceptually: pl1 1200 l1 32 pl2 l2 1200 32 Actually: (example addresses) Address Name Value 1200 l1 32 5232 pl1 1200 6044 pl2 1200 6134 l2 32 9

Dereferencing example *pl1 = 4 changes the value pointed at by pl1 We can change the thing pointed at without knowing what variable the address actually refers to (just change the value at this address ) The value of l1 changed without us mentioning l1 Conceptually: pl1 1200 l1 4 pl2 l2 1200 32 Actually: (example addresses) Address Name Value 1200 l1 4 5232 pl1 1200 6044 pl2 1200 6134 l2 32 10

Lecture Outline Arrays Only one-dimensional arrays Fit well with pointers char* and C-strings argv and argc 11

An introduction to (1D) arrays 12

Simple array creation (1) Create an uninitialised array: Add the square brackets [] at the end of the variable declaration, with a size inside the brackets e.g. array of 4 chars: char myarray[4]; e.g. array of 6 shorts: short secondarray[6]; e.g. array of 12 char*s: char* thirdarray[12]; Values of the array elements are unknown! NOT initialised! Whatever was left around in the memory locations 13

Simple array creation (2) Creating an initialised array: You can specify initial values, in {} E.g. 2 shorts, with values 4 and 1 short shortarray[2] = { 4, 1 }; E.g. 3 chars, with values o, n and e char chararray[3] = {'o','n','e'}; You can let the compiler work out the size: long longarray[] = (size 3) {100000, 5, 543}; char chararray2[] = (size 8) {'c','+','+','c','h','a','r', 0 }; 14

Arrays in memory C-Arrays are stored in consecutive addresses in memory (this is one of the few things that you CAN assume about data locations) Important point: From the address of the first element you can find the addresses of the others Example: -> short s[] = { 4,1 }; long l[] ={100000,5}; char ac[] = { 'c','+','+','c', 'h','a','r',0}; Address Name Value Size 1000 s[0] 4 2 1002 s[1] 1 2 1004 l[0] 100000 4 1008 l[1] 5 4 1012 ac[0] c 1 1013 ac[1] + 1 1014 ac[2] + 1 1015 ac[3] c 1 1016 ac[4] h 1 1017 ac[5] a 1 1018 ac[6] r 1 1019 ac[7] \0, 0 1 15

What we do and do not know The addresses of elements within an array are consecutive The relative locations of different arrays, or variables are NOT fixed Example: short s[] = { 4,1 }; long l[] ={100000,5}; char ac[] = { 'c','+','+','c', 'h','a','r',0}; With a different compiler you may instead get a different ordering, or gaps Address Name Value Size 1000 ac[0] c 1 1001 ac[1] + 1 1002 ac[2] + 1 1003 ac[3] c 1 1004 ac[4] h 1 1005 ac[5] a 1 1006 ac[6] r 1 1007 ac[7] \0, 0 1 1020 l[0] 100000 4 1024 l[1] 5 4 1030 s[0] 4 2 1032 s[1] 1 2 16

Accessing an array element Exactly the same as in Java, use [] E.g.: char ac[] = {'c','+','+','c', 'h','a','r', 0}; char c = ac[4]; Using what we have seen of pointers: char* pc1 = &(ac[0]); char* pc2 = &(ac[5]); 17

Java vs C arrays : length A problem in C/C++ (not Java): char ac[] = {'c','+','+','c','h','a', 'r', 0}; char c = ac[4]; char c2 = ac[12]; How long is my array? Java arrays include a length C arrays do not. You could: OOPS! 1. Label the last element with unique value? 2. Store the length somewhere? 3. If you can find the array size, work out the length 18

Java vs C arrays : bounds checks Java will throw an exception if you try to read/write beyond the bounds of an array C/C++ will let you read/overwrite whatever happens to be stored in the address if you read/write outside of array bounds Checking would take time, speed vs safety 19

Array names act as pointers The name of an array can act as a pointer to the first element in the array: char ac[] = {'c','+','+','c', 'h','a','r','\0'}; These are equivalent: char* pc3 = &(ac[0]); char* pc3 = ac; and make pc3 point to the first element. Note: &ac gives same value, different type 20

You can treat pointers as arrays Treating a pointer as an array: char ac[] = {'c','+','+','c', char* str = ac; 'h','a','r','\0'}; char c = str[4]; // c gets value h The type of pointer indicates the type of array The compiler trusts you It assumes that you know what you are doing i.e. it assumes that the pointer really has the address of the first element of an array So if you are wrong, you can break things 21

char* and C-String 22

C-string / char* We have treated char* as a string In fact it is a pointer to a char/character C-strings consist of an array of characters, terminated by a character value of zero The value zero is expressed by \0, or 0 NOT 0!!! (which is 48 in ASCII) Since arrays are in consecutive memory addresses, if we know the address of the first character in the array we can find all of the others H e l l o w o r l d! \n 0 23

char* as a string? The only reason that a char* can act like a string is: It was decided by someone that strings would be an array of characters with a 0 at the end But, consider the layout of an ASCII text file it makes sense this is the way that files are laid out There are various string functions in the C library The string functions assume that, the char* is a pointer to an array of chars, with a value 0 at the end to mark the end of the array E.g.: printf() to print a string strlen() to determine the length of a string strcpy() to copy a string into another string 24

Standard Library String Functions There are many string functions in the standard C library You should #include <cstring> to use them You need to know these and what they do Examples: strcat(s1,s2) strncat(s1,s2,n) strcmp(s1,s2) strncmp(s1,s2,n) strcpy(s1,s2) strncpy(s1,s2,n) strstr(s1,ch) strlen(s1) sprintf(str, ) Concatenates string s2 onto the end of s1 Concatenates up to n chars of string s2 to the end of s1 Compares two strings lexicographically Compares first n chars of string s1 with the first n chars of string s2 Copies string s2 into string s1 (assumes room!) Copies up to n characters from string s2 into string s1. Again assumes there is room! Returns a pointer to the first occurrence of char ch in string s1 Returns the length of s1 As printf, but builds the formatted string inside 25 string str. ASSUMES THERE IS ROOM!!!

String literals are arrays of chars Example: char* str = Hello!\n ; We have 2 things: A variable of type char*, called str An array of chars, with a 0 at the end for the string Address Value 10000 H 72 10001 e 101 10002 l 108 10003 l 108 10004 o 111 10005! 33 10006 \n? 10007 \0 0 Address Variable Value 2000 str 10000 26

You can manually create strings 1) Declare an array: char ac[] = { c, +, +, c, h, a, r, \0 }; 2) Get/store address of the first element: char* pc = ac; 3) Pass it to printf: printf( %s, pc); or just use array name: printf( %s, ac); Address Name Value Size 1000 ac[0] c 1 1001 ac[1] + 1 1002 ac[2] + 1 1003 ac[3] c 1 1004 ac[4] h 1 1005 ac[5] a 1 1006 ac[6] r 1 1007 ac[7] \0, 0 1 27

Initialisation of a char array You can initialise a char array from a string, so the following are equivalent: char c1[] = "Hello"; char c2[] = {'H','e','l','l','o','\0'}; This is a special case for char arrays It is different to: char* c3 = "Hello"; Which creates a POINTER, not an ARRAY A little confusing 28

Would this code work? #include <cstdio> int main() { char c1[] = "Hello"; char c2[] = { 'H', 'e', 'l', 'l', 'o', 0}; char* c3 = "Hello"; c1[0] = 'A'; c2[0] = 'B'; c3[0] = 'C'; } printf( "%s %s %s\n", c1, c2, c3 ); return 0; 29

Example #include <cstdio> int main() { char c1[] = "Hello"; char c2[] = { 'H', 'e', 'l', 'l', 'o', 0}; char* c3 = "Hello"; c1[0] = 'A'; c2[0] = 'B'; // c3[0] = 'C'; // Would probably segmentation fault } printf( "%s %s %s\n", c1, c2, c3 ); return 0; But it would compile! 30

Important! 31

Not all char*s are C-Strings This is important to remember A C-string is a char* which points to an array of characters with a 0 to mark the end Note: The parameter for main() char* argv[] IS an array of C-strings There is no way to know this from the parameter type, but we know (from other information) that main always gets passed an array of C-Strings 32

argc and argv 33

The Hello World Program #include <stdio.h> /* C file */ int main(int argc, char* argv[]) { printf("hello world!\n"); return 0; } C version #include <cstdio> /* C++ file */ int main(int argc, char* argv[]) { printf("hello world!\n"); return 0; } C++ version 34

Command line arguments int main(int argc, char *argv[]) argc: count of arguments including the filename argv[]: array of char*s argv[i]: a char* pointing to an array of chars To get a character from an array, use [] (or * to get first) e.g. command line: test hello world 14 Pointer to array of char*s argv argc = 4 Elements of argv are char*s (pointers to a char) argv[0] argv[1] argv[2] argv[3] The actual strings arrays of chars t e s t 0 h e l l o 0 w o r l d 0 1 4 0 35

Use of command line args What can we do with command line arguments? Treat them as a string: e.g. printf( Filename was %s\n, argv[0] ); Extract a character from them: e.g. argv[0] argv[1] char* param = argv[1]; printf( %c,%c,%c\n, param[0], *param, param[1]); printf( %c, %c\n, *argv[1], argv[1][0] ); Convert a string (not a char!) to an integer e.g. argv[3] int ival = atoi(argv[3]); t e s t 0 h e l l o 0 1 4 0 36

main() You don t need to declare the parameters for main int main() You can declare argv as: char** argv instead of char* argv[] The two forms are equivalent Both forms are pointers to pointers 37

Determining string length 38

Example: strlen() int strlen( char* str ) Get string length, in chars Check each character in turn until a \0 (or 0) is found, then return the length Length excludes the \0 int mystrlen( char* str ) { int i = 0; while ( str[i] ) i++; return i; } Address Name Value 1000 str[0] C 1001 str[1] 1002 str[2] s 1003 str[3] t 1004 str[4] r 1005 str[5] i 1006 str[6] n 1007 str[7] g 1008 str[8] \0, 0 Remember from lecture 2, integers can be used in conditions Value 0 means false, non-zero means true. 39

Summary 40

Pointers are important If you understand pointers, many other things will make sense Do not worry if it is not entirely clear now But please go through these slides until it is Pointers are not complex Just remember that they just store an address of something else And the type of thing that they point at I.e. They point to something else 41

Arrays You can easily create arrays Initialised or uninitialised Array elements are stored in consecutive areas of memory Very useful see next lecture No length is stored for an array If you need it you need to store it or work it out No bounds checking is performed when you use an array The compiler trusts you, so why waste time checking up on you? 42

Next lecture More pointers Pointers can be treated as arrays Pointer casting and printing Pointer arithmetic Functions: Declarations and definitions Passing pointers as parameters 43