CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

Similar documents
Arrays, Pointers, and Strings

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

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

Computer Programming: Skills & Concepts (CP) Strings

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Memory, Arrays & Pointers

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

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

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

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

Arrays and Pointers (part 1)

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

Arrays and Pointers (part 1)

Create a Program in C (Last Class)

CSE 230 Intermediate Programming in C and C++ Recursion

Array Initialization

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

211: Computer Architecture Summer 2016

CSE 230 Intermediate Programming in C and C++ Functions

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Procedural Programming & Fundamentals of Programming

Computer Science & Engineering 150A Problem Solving Using Computers

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

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

Dynamic memory allocation

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

CSC 2400: Computer Systems. Arrays and Strings in C

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

CSE 230 Intermediate Programming in C and C++

Introduction to Programming Block Tutorial C/C++

CSC 2400: Computer Systems. Arrays and Strings in C

8. Characters, Strings and Files

Course organization. Course introduction ( Week 1)

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Computers Programming Course 11. Iulian Năstac

Introduction to string

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

20 Dynamic allocation of memory: malloc and calloc

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

C programming basics T3-1 -

Procedural Programming

CSE 230 Intermediate Programming in C and C++

Fundamentals of Programming & Procedural Programming

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Pointers. Pointers. Pointers (cont) CS 217

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

ARRAYS(II Unit Part II)

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

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

Intermediate Programming, Spring 2017*

Lesson #8. Structures Linked Lists Command Line Arguments

DAY 3. CS3600, Northeastern University. Alan Mislove

Fundamentals of Programming

CSE 230 Computer Science II (Data Structure) Introduction

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

Fundamental of Programming (C)

Contents of Lecture 3

Kurt Schmidt. October 30, 2018

Dynamic memory allocation (malloc)

ESC101N: Fundamentals of Computing End-sem st semester

Lecture 05 Pointers ctd..

CS1100 Introduction to Programming

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Understanding Pointers

Characters and Strings

CYSE 411/AIT681 Secure Software Engineering Topic #10. Secure Coding: Integer Security

2/9/18. Readings. CYSE 411/AIT681 Secure Software Engineering. Introductory Example. Secure Coding. Vulnerability. Introductory Example.

2/9/18. CYSE 411/AIT681 Secure Software Engineering. Readings. Secure Coding. This lecture: String management Pointer Subterfuge

Pointers, Arrays, and Strings. CS449 Spring 2016

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

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

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

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

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

ECE551 Midterm Version 1

Dynamic Allocation in C

Arrays and Pointers in C. Alan L. Cox

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

ONE DIMENSIONAL ARRAYS

Pointers. Pointer References

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

C & Data Structures syllabus

Principles of C and Memory Management

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

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

Multiple Choice Questions ( 1 mark)

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

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

C programming for beginners

Transcription:

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/

Pointer Arithmetic and Element Size If p is a pointer to a particular type, then the expression p + 1 yields the correct machine address for storing or accessing the next variable of that type. Valid operations: p + i, ++p, p += 2 etc. If p and q are both pointing to elements of an array, then p - q yields the int value representing the number of array elements between them Shebuti Rayana (CS, Stony Brook University) 2

Example: Pointer Arithmetic int i = 7,*p = &i, *r; double a[2]={0.1,0.2},*q, *s; r = p + 1; q = a; //q points to a[0] s = q + 1; // s = &a[1] printf( %d\n,(int)r - (int)p); printf( %d\n,(int)s - (int)q); Printf( %d\n,s - q); Shebuti Rayana (CS, Stony Brook University) 3

Example: Pointer Arithmetic printf( %d\n,(int)r - (int)p); 4 printf( %d\n,(int)s - (int)q); 8 Printf( %d\n, s - q); 1 The difference in terms of array elements is 1, but the difference in memory locations is 8 as size of double is 8. Shebuti Rayana (CS, Stony Brook University) 4

Arrays as Function Arguments In function definition, the parameter that is declared as an array is a pointer. When an array is passed to a function the base address (&a[0]) is passed, not the elements of the array are copied. Example: Shebuti Rayana (CS, Stony Brook University) 5

Arrays as Function Argument Following two are same: double sum(double a[], int n) double sum(double *a, int n) Array declaration = pointer declaration in parameter list, but not inside the function body From the caller: sum(a, n);or sum(&a[0], n); both are correct sum(&a[7], k - 7) = a[7], a[8],, a[k-1] Shebuti Rayana (CS, Stony Brook University) 6

An Example: Bubble Sort Bubble sort is expensive takes O(n 2 ) Shebuti Rayana (CS, Stony Brook University) 7

Each Pass of Bubble Sort Unsorted Data 7 3 66 3-5 22-77 2 First Pass -77 7 3 66 3-5 22 2 Second Pass -77-5 7 3 66 3 2 22 Third Pass -77-5 2 7 3 66 3 22 Fourth Pass -77-5 2 3 7 3 66 22 Fifth Pass -77-5 2 3 3 7 22 66 Sixth Pass -77-5 2 3 3 7 22 66 Seventh Pass -77-5 2 3 3 7 22 66 Shebuti Rayana (CS, Stony Brook University) 8

Dynamic Memory Allocation Two standard library functions in stdlib.h calloc():contiguous memory allocation malloc():memory allocation Example usage of calloc(): int *a; int n; scanf( %d,&n); a = calloc(n,sizeof(int)); The space is initialized with all bits set to 0 Shebuti Rayana (CS, Stony Brook University) 9

Dynamic Memory Allocation (cont.) Example malloc(): a = malloc(n*sizeof(int)); Unlike calloc(), malloc() does not initialize the memory locations In malloc()is faster Programmer must call free()to free the allocated memory with them Example: free(a); Shebuti Rayana (CS, Stony Brook University) 10

Strings One-dimensional arrays of type char terminated with end-of-string \0 or null (byte with all bits off) Size must include space for \0 String constants are written in double quotes, e.g., abc (character array of size 4) String constant: a (size 2) vs character constant: a (size 1) Example: char *p = abc ; printf( %s %s\n, p, p+1); output: abc bc Shebuti Rayana (CS, Stony Brook University) 11

Strings (cont.) A string constant can be treated as a pointer abc [1] and *( abc + 2) are legal Arrays and pointers differences: char *p = abc ; char s[] = abc ; p 4 bytes a b c \0 a b c \0 s 4 bytes 4 bytes Shebuti Rayana (CS, Stony Brook University) 12

Example: String Shebuti Rayana (CS, Stony Brook University) 13

Library Functions for Strings C provide numerous string handling functions in standard library with header string.h char *strcat(char *s1, canst char *s2); int strcmp(const char *s1, const char *s2); S1 is lexicographically greater, equal or less than s2 char *strcpy(char *s1, const char *s2); size_t strlen(const char *s); 4 bytes machine size_t is unsigned int Shebuti Rayana (CS, Stony Brook University) 14

Implementation: strlen() size_t strlen(const char *s) { for (n = 0; *s!= '\0'; ++s) ++n; return n; } Shebuti Rayana (CS, Stony Brook University) 15

Implementation: strcpy() char *strcpy(char *sl,register const char *s2) { register char *p = s1; while(*p++ = *s2++) ; return s1; } Shebuti Rayana (CS, Stony Brook University) 16

Implementation: strcat() char *strcat(char *sl,register const char *s2) { register char *p = s1; while(*p) ++p; while(*p++ = *s2++) ; return s1; } Shebuti Rayana (CS, Stony Brook University) 17

String: Declaration and Initialization char s1[] = "beautiful big sky country ; char s2[] = "how now brown cow"; Expression strlen(s1) 25 strlen(s2+8) 9 strcmp(s1, s2) Statements printf( %s,s1+10) strcpy(s1+10, s2+8) strcat(s1, s! ) printf( %s,s1) Value Negative integer What gets printed Big sky country Beautiful brown cows! Shebuti Rayana (CS, Stony Brook University) 18

Two Dimensional Arrays int a[3][5]; Expression Equivalent to a[i][j] *(a[i]+j) (*(a+i))[j] *((*(a+i))+j) *(&a[0][0]+5*i+j) Three Dimensional Arrays int a[7][9][2] Expression Equivalent to a[i][j][k] *(&a[0][0][0] + 9*2*i + 2*j + k) Shebuti Rayana (CS, Stony Brook University) 19

Arrays of Pointers Arrays of pointers have many use An array of char * is considered as array of strings Example: char *car_make[9]; char *car_make[9] = {"Suzuki","Toyota","Nissan","Tata","BMW","Audi","Chevrolet","Honda","Mahindra"}; Sort the strings in lexicographic order Shebuti Rayana (CS, Stony Brook University) 20

Sort in Lexicographic: Example Void sort_word(char *w[], int n) { } int i, j; for(i=0;i<n;++i){ } for(j=i+1;j<n;++j){ } if(strcmp(w[i],w[j])>0) swap(&w[i],&w[j]); void swap(char **p, char **q){ char *temp; temp = *p; *p = *q; *q = temp; } Shebuti Rayana (CS, Stony Brook University) 21

Arguments to main() Two arguments named argc and argv can be used with main()to communicate with the OS Example: main(int argc, char *argv[]) int argc provides a count of the number of command line arguments Array argv is an array of pointers that are the words that make up the command line. Because the element argv [0] contains the name of the command itself, the value of argc is at least 1. Shebuti Rayana (CS, Stony Brook University) 22

Ragged Arrays An array of pointers whose elements are used to point to arrays of varying sizes is called a ragged array. char a[2][15] = {"abc:", "a is for apple"}; char *p[2] = {"abc:", "a is for apple"}; Shebuti Rayana (CS, Stony Brook University) 23

Functions as Arguments In C, pointers to functions can be passed as arguments, used in arrays, returned from function Example: you want to do an operation with a variety of functions like ' ()* f # (k) In one instance f k = sin(k), in another instance f k = / ( Shebuti Rayana (CS, Stony Brook University) 24

Implementation: Function as Argument double sum_square(double f(double x), int m, int n){ } int k; double sum = 0.0; for (k = m; k <= n; ++k) sum += f(k) * f(k); return sum; double f(double x){ return 1/x; } sum_square(f, 1, 100) sum_square(sin, 1, 100) Equivalent double sum_square(double (*f)(double x), int m, int n) Shebuti Rayana (CS, Stony Brook University) 25

Type Qualifier const and volatile If a variable is declared with a const type it can not be changed const int k = 3; The volatile variables are modified with some unspecified ways by the hardware. Used seldom. Shebuti Rayana (CS, Stony Brook University) 26