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

Similar documents
Pointers, Arrays, and Strings. CS449 Spring 2016

Create a Program in C (Last Class)

Arrays, Strings, & Pointers

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

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


ARRAYS(II Unit Part II)

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

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

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Computer Science & Engineering 150A Problem Solving Using Computers

CS 222: Pointers and Manual Memory Management

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

C Characters and Strings

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

1 Pointer Concepts. 1.1 Pointer Examples

Fundamentals of Programming

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

Principles of C and Memory Management

ECE 15B COMPUTER ORGANIZATION

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

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

8. Characters, Strings and Files

Computer Programming: Skills & Concepts (CP) Strings

Characters and Strings

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

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

Fundamental of Programming (C)

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

ONE DIMENSIONAL ARRAYS

Arrays and Strings. CS449 Fall 2017

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

CS201- Introduction to Programming Current Quizzes

DAY 3. CS3600, Northeastern University. Alan Mislove

Princeton University Computer Science 217: Introduction to Programming Systems. Modules and Interfaces

In Java we have the keyword null, which is the value of an uninitialized reference type

Class Information ANNOUCEMENTS

Memory, Arrays & Pointers

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

CS 11 C track: lecture 5

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

ECE551 Midterm Version 1

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

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Fundamentals of Programming & Procedural Programming

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Dynamic memory allocation

CS 61c: Great Ideas in Computer Architecture

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Fundamental of Programming (C)

Computers Programming Course 11. Iulian Năstac

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

Programming. Pointers, Multi-dimensional Arrays and Memory Management

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

Arrays and Pointers (part 1)

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

Week 5. Muhao Chen.

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Computer Programming Unit 3

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

Dynamic memory allocation (malloc)

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

High Performance Programming Programming in C part 1

Why arrays? To group distinct variables of the same type under a single name.

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

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

Procedural Programming & Fundamentals of Programming

Lecture 07 Debugging Programs with GDB

Intermediate Programming, Spring 2017*

Arrays and Pointers (part 1)

Lecture 05 Pointers ctd..

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

211: Computer Architecture Summer 2016

CS24 Week 2 Lecture 1

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

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

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Memory Management. CSC215 Lecture

Dynamic Memory CMSC 104 Spring 2014, Section 02, Lecture 24 Jason Tang

Arrays and Pointers in C. Alan L. Cox

CSC 1600 Memory Layout for Unix Processes"

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

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

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Computers Programming Course 10. Iulian Năstac

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Intermediate Programming, Spring 2017*

Pointers, Dynamic Data, and Reference Types

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

Array Initialization

Chapter 8: Character & String. In this chapter, you ll learn about;

Transcription:

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Outline Review pointers New: Strings New: Variable Scope (global vs. local variables) New: C Memory model Midterm exam next week! 2 1

Recap: Pointers int *ptr; Pointers are variables that store memory address of other variables Type of variable pointed to depends on type of pointer: int *ptr points to an integer value char *ptr points to character variable Can cast between pointer types: myintptr = (int *) malloc(sizeof(..)*..); void *ptr has an unspecified type (generic pointer); must be cast to a type before used 3 Recap: Pointers Two main operations * dereference: get the value at the memory location stored in a pointer & address of: get the address of a variable int *myptr = &myvar; Pointer arithmetic: directly manipulate a pointer's content to access other locations Use with caution!: can access bad areas of memory and cause a crash However, it is useful in accessing and manipulating data structures Can have pointers to pointers int **my2darray; 4 2

Why Pointers change values of variable(s) passed into functions void set_to_zero(int a) a = 0; void main() int a; a = 5; set_to_zero(a); printf("%d\n", a); void set_to_zero(int *a) *a = 0; void main() int a; a = 5; set_to_zero(&a); printf("%d\n", a); 5 Strings There is no string type in C! Instead, strings are implemented as arrays of characters: char* or char [] Enclosed in double quotes Terminated by NULL character ( \0') "Hello" same as char str[] = 'H', 'e', 'l', 'l', 'o', \0' 6 3

Strings: printf() and scanf() placeholder %s int main() char name[10]; scanf("%s", name); // read one word, skip spaces, newlines, tabs, etc. printf("%s", name); char months[12][10] = "January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ; 7 In Class Exercise 7 1 Write a program that takes a word less than 25 characters long and print a statement like this: Input a word: fractal fractal starts with the letter f. 8 4

String library <string.h> has functions for manipulating null terminated strings. int strlen(const char *s): returns length of s char *strcpy(char *s1, const char *s2): copies s2 into s1 (Check if s1 has enough space. ) int strcmp(const char *s1, const char *s2): compares s1 and s2 (return 0 if they are the same,!=0 if they are different) char *strcat(char *s1, const char *s2): appends s2 to s1 (Check if s1 has enough space. ) 9 Example strlen() #include <stdio.h> #include <string.h> int main() int t; t = strlen("czech Republic"); // 14 not counting \0 printf("%d",t); 10 5

Example strcmp() #include <stdio.h> #include <string.h> int main() char szkey[] = "apple"; char szinput[80]; for (;;) printf("guess my favorite fruit?\n"); scanf( %s, szinput); if (strcmp (szkey,szinput) == 0) break; printf("correct answer!"); 11 Example strcpy() #include <stdio.h> #include <string.h> int main () char str1[]="sample string"; char str2[40]; char str3[40]; strcpy (str2,str1); strcpy (str3,"copy successful"); printf ("str1: %s\nstr2: %s\nstr3: %s\n", str1,str2,str3); 12 6

Example strcat() #include <stdio.h> #include <string.h> int main () char str[80]; strcpy (str,"these "); strcat (str,"strings "); strcat (str,"are "); strcat (str,"concatenated."); printf( %s, str); 13 In Class Exercise 7 2 Write the int strlen(const char *s) function. This function takes a string and returns the number of characters, not counting the terminating null. #include <stdio.h> int strlen(const char* s) /* your code goes here */ int main() char* p = "hello, world"; printf("%d\n", strlen(p)); printf("%d\n", strlen(p + 7)); 14 7

More String library functions char* strncpy(char *s1, const char *s2, size_t n): copies the first n characters in s2 into s1 int strncmp(const char* s1, const char* s2, size_t n): compares the first n characters in s1 and s2 (return 0 if they are the same,!=0 if they are different) char* strncat(char *s1, const char *s2, size_t n): appends the first n characters in s2 to s1 15 Example strncmp() #include <stdio.h> #include <string.h> int main () char str[3][5] = "R2D2", "C3PO", "R2A6" ; int n; puts ("Looking for R2 astromech droids..."); for (n=0 ; n<3 ; n++) if (strncmp(str[n],"r2xx",2) == 0) printf("found %s\n",str[n]); 16 8

Global (External) vs. Local Variables A local variable is declared inside a function body. It is local to a function, i.e., it only exists within this function. int sum_digits(int n) // local variable int sum = 0; while (n > 0) sum += n % 10; n /= 10; return sum; void print_sum(int sum) printf( sum is %d\n, sum); A global variable is declared outside of any function. It can be accessed anywhere in the program int sum; // global variable void sum_digits(int n) while (n > 0) sum += n % 10; n /= 10; void print_sum() printf( sum is %d\n, sum); 17 Variable Scope The scope of a variable is the region within a program where it is defined and can be used. program scope (global var); function/block scope (local var) int x; void f(void) int x; if ( ) function scope of y void f2() int z; block scope of z program scope of x 18 9

Variable Scope Example int i; void f(int i) i = 1; void g() int i=2; if (i > 0) int i; i = 3; i = 4; void h() i = 5; 19 Pros & Cons of Global Variables Why not declare all variables global? External variables are very convenient when functions (e.g., sum_digits() & print_sum()) must share a variable. Passing variables between functions involves writing more code. What are the tradeoffs for global vs. local variables? Say if you need to change the type of a global variable (must check all functions that use this variable) Say if you need to debug a glob al variable that has a wrong value (which one is the guilty function?) Say if you want to reuse a function (in another program) that rely on global variables 20 10

In Class Exercise 7 3 Write a simple game playing program using a global variable. The program generates a random number between 1 and 100, which the user attempts to guess in as few tries as possible. Your program should have the following input & output: Guess the secret number between 1 and 100 Enter guess: 55 Too low, try again. Enter guess: 65 Too high, try again. Enter guess: 61 You won in 3 guesses! Play again? (Y/N) Y Guess the secret between 1 and 100 Enter guess: 31 21 More on Exercise 7 3 You program should have the following global variable and functions. #include <stdio.h> #include <time.h> int secret_num; // global var to store the secret num void init_num_generator() srand(time(null)); // init the seed of random number generator /* select a new secret number */ void new_secret_num() secret_num = rand() % 100 + 1; // a random number 0-99 /* continuously read user guesses and tell too low/high/correct */ void read_guesses(); 22 11

Static Local Variables A permanent storage inside a function so its value is retained throughout the program execution (vs. local variable, its storage is gone at the end of the function) void sumit(void) static int sum = 0; int num; printf("\nenter a number: "); scanf("%d", &num); sum+=num; printf("the current sum is: %d",sum); int main() int i =0; printf("enter 5 numbers to be summed\n"); for(i = 0; i<5; ++i) sumit(); printf("program completed\n"); 23 C Memory Model Program code Function variables Arguments Local variables Return location Global Variables Statically allocated Dynamically allocated int fact (int n) return(n*fact(n-1)); void main() fact(5); 24 12

The Stack Stores Function local variables Temporary variables Arguments for next function call Where to return when function ends 25 The Stack Managed by compiler One stack frame each time function called Created when function called Stacked on top (under) one another Destroyed at function exit 26 13

What can go wrong? Recall that local variables are stored on the stack Memory for local variables is deallocated when function returns Returning a pointer to a local variable is almost always a bug! char *my_strcat(char *s1, char *s2) char s3[1024]; strcpy(s3, s1); strcat(s3, s2); return s3; 27 What Can Go Wrong? Run out of stack space Unintentionally change values on the stack In some other function's frame Even return address from function Access memory even after frame is deallocated 28 14

The Heap C can use space in another part of memory: the heap The heap is separate from the execution stack Heap regions are not deallocated when a function returns The programmer requests storage space on the heap C never puts variables on the heap automatically But local variables might point to locations on the heap Heap space must be explicitly allocated and deallocated by the programmer 29 malloc() Library function in <stdlib.h> Stands for memory allocate Requests a memory region of a specied size Syntax: void *malloc(int size) void * is generic pointer type 30 15

Usage int main() int *p = (int *) malloc(10 * sizeof(int)); if (p == NULL) // do cleanup // do something free(p); Good to check the return value from malloc() Must explicitly free memory when no longer in use 31 What Can Go Wrong? Run out of heap space: malloc returns 0 Unintentionally change other heap data Access memory after free'd free memory twice 32 16

Usage #include <stdio.h> #include <stdlib.h> int main() int *p = (int *) malloc(10 * sizeof(int)); if (p == NULL) // do cleanup // do something if (p!= NULL) free(p); p = NULL; 33 Multidimensional Array On the stack: int a[10][20]; Initialization: int a[][] = 1, 2, 3, 4, 5, 6; Accessing the array: a[1][0] On the heap int **a = (int **) malloc(10 * sizeof(int *)); for (int i = 0; i < 10; ++i) a[i] = (int *) malloc(20 * sizeof(int)); Don't forget to free them! 34 17

Exercise 7 4 Write a program that (1) asks for the number of friends, (2) asks for a name, and (3) checks a series of strings to see which one matches the names of friends. Please use Use malloc() to create this multi dimensional array of friends names. You can assume that the friends names are less than 10 characters. Use <string.h> library Use scanf( %s,..) to read a name separated by one or more whitespaces Input the number of your friends: 4 John Polly Peter Jane Input a name: Jane Jane is friend #4 Input a name: Mary Mary is not a friend 35 18