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

Similar documents
Lesson #8. Structures Linked Lists Command Line Arguments

Intermediate Programming, Spring 2017*

CS 241 Data Organization Pointers and Arrays

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

High Performance Programming Programming in C part 1

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

Work relative to other classes

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CSE 333 Lecture 7 - final C details

DAY 3. CS3600, Northeastern University. Alan Mislove

PRINCIPLES OF OPERATING SYSTEMS

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

Kurt Schmidt. October 30, 2018

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

Lecture 04 Introduction to pointers

Pointers, Dynamic Data, and Reference Types

8. Characters, Strings and Files

CS C Primer. Tyler Szepesi. January 16, 2013

CS 261 Fall Mike Lam, Professor. Structs and I/O

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C programming basics T3-1 -

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

CSC 2400: Computer Systems. Arrays and Strings in C

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

Procedural programming with C

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

EM108 Software Development for Engineers

CSC 2400: Computer Systems. Arrays and Strings in C

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

CS 61c: Great Ideas in Computer Architecture

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

Programming in C. Pointers and Arrays

Arrays and Pointers in C. Alan L. Cox

Language comparison. C has pointers. Java has references. C++ has pointers and references

Memory, Arrays & Pointers

Introduction to string

Pointers. Pointers. Pointers (cont) CS 217

Dynamic memory allocation (malloc)

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

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

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

Arrays, Strings, & Pointers

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

CS Programming In C

today cs3157-fall2002-sklar-lect05 1

Pointers. Pointer References

Programming in C - Part 2

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

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

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

Goals of this Lecture

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


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

Character Strings. String-copy Example

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

Course organization. Course introduction ( Week 1)

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

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

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

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

Understanding Pointers

BSM540 Basics of C Language

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

JTSK Programming in C II C-Lab II. Lecture 3 & 4

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

PDS Class Test 2. Room Sections No of students

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

Pointers, Arrays, and Strings. CS449 Spring 2016

DS Assignment I. 1. Set a pointer by name first and last to point to the first element and last element of the list respectively.

211: Computer Architecture Summer 2016

Intermediate Programming, Spring 2017*

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Data Representation and Storage. Some definitions (in C)

Variation of Pointers

Pointers. 10/5/07 Pointers 1

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C for C++ Programmers

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

Arrays and Pointers (part 1)

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

C-LANGUAGE CURRICULAM

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

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

More Pointers Week 11

PROGRAMMAZIONE I A.A. 2017/2018

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

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

CS61, Fall 2012 Section 2 Notes

Lectures 5-6: Introduction to C

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Transcription:

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

Pointers 2

Pointers Pointers are an address in memory Includes variable addresses, constant addresses, function address... It is a data type just like any other (int, float, double, char) On 32-bit machines, pointers are 4 bytes in size On 64-bit machines, pointers are 8 bytes Pointers point to a particular data type The compiler checks pointers for correct use just as it checks int, float, etc. 3

Declaring pointers No data type called pointer Instead, use * to denote a pointer int *ptrx; // pointer to data type int float *ft; // pointer to data type float short *st; // pointer to data type short Compiler associates pointers with corresponding data types Variables ptrx and ft contain addresses that hold int and float values How big (in bytes) are ptrx, ft, and st? 4

Referencing/dereferencing pointers How can you create a pointer to a variable? Use &, which returns the address of the argument int y = 7; int *x = &y; // assigns the address of y to x How can you get the value pointed to? Dereference the pointer using * (unf., * is used both in definitions and here) Go to the address which is stored in x, and return the value at that address. int y = 7; // y is 7 int *x = &y; // x is the memory address of y int z = *x; // z is now 7 (*a)++; // increments the value pointed to a *(a + 1); // accesses the value pointed to by the address (a + 1) 5

Pointer quiz int y = 10; int x = y; y++; x++; What is the value of y? int y = 10; int *x = &y; y++; (*x)++; What is the value of y? 6

Arrays and pointers Compiler associates the address of the array to/with the name int temp[34]; Array name (temp) is the pointer to the first element of array To access the nth element of the array: Address = starting address + n * size of element Starting address = name of the array Size of element = size of data type of array array[10] de-references the value at the nth location in the array int temp[10]; // Assume temp = 100 (memory address) temp[5] = *(100 + (4 x 5)) = *(120) // dereference address 120 7

Passing arrays Passing an array passes a pointer Passing an array as an argument passes the address Hence arrays are always passed by reference int general (int size, int name []); //Expects a pointer to an int array int general (int size, int *name); //Expects a pointer to an int void foo(int a[]) { a[0] = 17; } int b[1] = { 5 }; foo(b); What is the value of b[0]? 8

Functions and pointers Functions must return a value of the declared type Just like variables, functions can return a pointer What does the following function return? float *calc_area (float radius); Function formal arguments may be of type pointer: double calc_size (int *stars); For example, scanf takes in parameters as pointers: int scanf(const char *format,...); // int*, int* scanf("%d%f ", &x, &f); 9

Passing in pointers Why pass a variable address at all and complicate functions? By design we can return only one value Sometimes we need to return back more than one value For example, consider scanf("%d%f ", &x, &f); Three values are returned (in x, f, and the return value) Pointers allows us to return more than one value 10

Pointer arithmetic Pointers can be added to and also subtracted from Pointers contain addresses Adding to a pointer goes to next specified location (dep. on data type) <data type> *ptr; ptr + d means ptr + d * sizeof (<data type>); For example int *ptr; ptr + 2 means ptr + 2*4 which is ptr + 8 char *ptr; ptr + d means ptr + 2*1 which is ptr + 2 11

Example # include <stdio.h> int main () { int *i; int j = 10; i = &j; printf ("address of j is : %p\n", i); printf ("address of j + 1 is : %p\n", i + 1); } What is the output? $./a.out address of j is : 0xbffffa60 address of j + 1 is : 0xbffffa64 $ Note that j + 1 is actually 4 more than j 12

Strings 13

Character strings A sequence of character constants such as This is a string Each character is a character constant in a consecutive memory block Representation in memory T h i s i s a s t r i n g \0 Each character is stored in ASCII, in turn is stored in binary Character strings are actually character arrays A string constant is a character array whose elements cannot change char *msg = "This is a string"; 14

Strings as arrays char *msg = "This is a string!"; The variable msg is associated with a pointer to the first element msg is an array of 19 characters \0 is also considered a character Appended to each string by the compiler Used to distinguish strings in memory, acts as the end of the string Also called the NULL character Character pointers char *ptr; ptr = "This is a string"; ptr is a character pointer containing the address of the first character (T) Which is the first element of the character array containing "This is a string" 15

String functions Pointers to character strings can be manipulated as other pointers char *point1, *point2 = welcome ; point1 = point2; if (point1 == point2) { // valid, but will only compare pointers Utilities provided as part of the C standard libraries Most of the functions can be found in the header file string.h or stdlib.h Always check the man page to find out the header file of that function bash$ man 3 strlen 16

strcmp, strlen int strcmp (char *ptr1, char *ptr2) Compares strings pointed to by ptr1 and ptr2 Returns 0 if identical strings, non-zero otherwise. if (strcmp ( welcome, cs132 ) == 0) {... } char *ptr = welcome ; if (strcmp ( welcome, ptr) == 0) // true int strlen (const char *ptr) Returns count of characters in string. Does not include NULL character in count int x = strlen ( welcome ); // x has value 7 17

strcpy char *strcpy (char *ptr1, char *ptr2) Copies entire string pointed to by ptr2 onto ptr1. Returns address of string at ptr1 (we had this anyway, but we get it back anyway, useful sometimes) char *ptr1 = welcome ; char ptr2 [10]; strcpy (ptr2, ptr1); Now ptr2 has *a copy* of the string welcome IMPORTANT: ptr1 must have enough space to contain the entire string char ptr[4] = Hey ; // string of 4 characters strcpy (ptr, hello ); // (likely) RUN-TIME ERROR 18

Getting numbers from strings int atoi (const char *ptr); Converts an alphanumeric string to an integer if possible Returns 0 and sets global variable errno if an error occurs double atof (const char *ptr); Converts an alphanumeric string to a double if possible int a = atoi("17"); //a is now 17 double b = atof("89.29393"); //b is now 89.29393 19

Structures 20

Structures An aggregate data type which contains a fixed number of components Declaration: struct name { // components // more components }; For example struct dob { int month; int day; int year; }; Each dob has a month, day, and year (ints) inside it 21

Using structures Declare variables using struct keyword All internal variables are allocated space struct dob d1, d2; Access member values using. notation d1.day = 10; d2.year = 1976; printf("%d\n", d2.year); A structure can be assigned directly to another structure struct dob d1, d2; d1.day = 10; d1.month = 12; d1.year = 1976; d2 = d1; // now d2 has the same values as d1 for its fields. 22

Operations on structures Cannot check to see if two structures are alike directly struct dob d1, d2; if (d1 == d2) // WRONG!!! To compare, we need to check every internal value Cannot print structures directly Must print one field at a time Pointers to structures use the -> notation struct dob *d1; d1->year = 1976; d1->day = 26; d1->month = 6; 23

A little more on structures Can be initialized field by field or during declaration struct dob d1 = {26, 06, 1976}; Can create arrays of structures struct dob d1[10]; // array of 10 structs dob And access them in the usual manner d1[1].day = 26; d1[1].month = 6; d1[1].year = 1976; 24

Making a structure into a type Type definition allows an alias for an existing type identifier typedef type name; For example typedef struct dob_s { int day; int month; int year; } dob; Now, can simply do dob my_dob; my_dob.year = 17; 25

C command line 26

argc and argv How can we access the command line? Done using two variables argc and argv, passed as an argument to main int main (int argc, char *argv[]) argc contains the total number of arguments, which includes the command argv contains the list of pointers to all the arguments (length argc) Who fills up these two variables? Done by the OS argv is automatically resized to include the whole command 27

Using the arguments # include <stdio.h> int main (int argc, char *argv[]) { int i; printf ("The number of arguments = %d\n", argc); for (i = 0; i < argc; i++) printf ("%d. %s\n", i, argv[i]); // print each argument. } Will print out each of the arguments passed in bash$./a.out The number of arguments = 1 0../a.out bash$$./a.out first second The number of arguments = 3 0../a.out 1. first 2. second 28