C Fundamentals! C vs. Java: Design Goals. q Java design goals! q Implications for Java! language, machine language, hardware!

Similar documents
Program Building. Goals for this Lecture. Help you learn about: Program structure. Detecting and reporting failure

CSC 2400: Computing Systems

Towards the Hardware"

CSC 2400: Computer Systems. Arrays and Strings in C

CSC 2400: Computer Systems. Arrays and Strings in C

Goals of this Lecture

CSC 1600 Memory Layout for Unix Processes"

Variables, Pointers, and Arrays

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C

Princeton University Computer Science 217: Introduction to Programming Systems. Goals of this Lecture. A Taste of C. Agenda.

Assembly Language Programming - III

(2) Accidentally using the wrong instance of a variable (sometimes very hard one to find).

ch = argv[i][++j]; /* why does ++j but j++ does not? */

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Short Notes of CS201

Question 4.2 2: (Solution, p 5) Suppose that the HYMN CPU begins with the following in memory. addr data (translation) LOAD 11110

CS201 - Introduction to Programming Glossary By

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Lecture 2: C Programming Basic

Pointers, Dynamic Data, and Reference Types

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

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

BSM540 Basics of C Language

Fundamental of Programming (C)

Fundamental of Programming (C)

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Memory and C/C++ modules

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Draft. Chapter 1 Program Structure. 1.1 Introduction. 1.2 The 0s and the 1s. 1.3 Bits and Bytes. 1.4 Representation of Numbers in Memory

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

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

SWEN-250 Personal SE. Introduction to C

A Fast Review of C Essentials Part I

C-LANGUAGE CURRICULAM

Princeton University Computer Science 217: Introduction to Programming Systems. A Taste of C

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

Part V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

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

CSCI 171 Chapter Outlines

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Procedural programming with C

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

Arrays and Pointers in C. Alan L. Cox

Lecture 03 Bits, Bytes and Data Types

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

An Ungentle Introduction to C

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Intel assembly language using gcc

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

C Programming Review CSC 4320/6320

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

CMPSC 311- Introduction to Systems Programming Module: Introduction to C

DECLARAING AND INITIALIZING POINTERS

o Code, executable, and process o Main memory vs. virtual memory

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

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

Computer Science 217 Final Exam May 15, :30pm-4:30pm

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

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

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Object-Oriented Programming

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

CIT Week13 Lecture

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

Arrays, Strings, & Pointers

CPEG421/621 Tutorial

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

Lecture 2: C Programm

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

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

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Computer Programming Unit v

Standard File Pointers

Lab 3. Pointers Programming Lab (Using C) XU Silei

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

Goals of this Lecture

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

25.2 Opening and Closing a File

BLM2031 Structured Programming. Zeyneb KURT

Computers Programming Course 5. Iulian Năstac

Processes. Johan Montelius KTH

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

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

CSE 374 Programming Concepts & Tools

C++ for Java Programmers

Transcription:

C Fundamentals C vs. Java: Design Goals q Java design goals q Support object-oriented programming q Allow program to be executed on multiple operating systems q Support using computer networks q Execute code from remote sources securely q Adopt the good parts of other languages (esp. C and C++) q Implications for Java q Good for application-level programming q High-level q Virtual machine insulates programmer from underlying assembly language, machine language, hardware q Portability over efficiency q Security over efficiency q Security over flexibility 1

C vs. Java: Design Goals q C design goals q Support structured programming q Support development of the Unix OS and Unix tools q As Unix became popular, so did C q Implications for C q Good for system-level programming q q q q q But often used for application-level programming sometimes inappropriately Low-level q Close to assembly language; close to machine language; close to hardware Efficiency over portability Efficiency over security Flexibility over security C vs. Java: Design Goals q Differences in design goals explain many differences between the languages q C s design goal explains many of its eccentricities q We ll see examples throughout the course 2

Circle Program q File circle.c: #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Building and Running q To build (preprocess, compile, assemble, and link): $ gcc circle.c o circle q To run: $./circle Enter the circle's radius: 5 A circle with radius 5 has diameter 10 and circumference 31.415900. Typed by user 3

Steps in the Build Process q To build one step at a time: Preprocess: circle.c circle.i Compile: circle.i circle.s Assemble: circle.s circle.o $ gcc E circle.c > circle.i $ gcc S circle.i $ gcc c circle.s $ gcc circle.o o circle Link: circle.o circle q Why build one step at a time? q Helpful for learning how to interpret error messages q Permits partial builds (described later in course) The Preprocessor s View q File circle.c: #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; 4

Results of Preprocessing q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Where are the DEFINITIONS of printf() and scanf()? What is Wrong? #include <stdio.h> int main() SomeFunction(); return 0; void SomeFunction() printf( My prototype is missing\n ); 5

The Compiler s View q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; The Compiler s View (cont.) q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; & ( address of ) operator Explained later in course, with pointers 6

What is Wrong? #include <stdio.h> int main() int sum; for(int i = 1; i <= 10; i++) sum = sum + i; int fact; for(i = 1; i <= 10; i++) fact = fact * i; return 0; The Compiler s View (cont.) q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; 7

The Compiler s View (cont.) q File circle.i: int printf(char*, ); int scanf(char*, ); int main(void) int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Results of Compiling q File circle.s:.lc0:.lc1: main:.section.rodata.string "Enter the circle's radius:\n".string "%d".section.text.globl main.type main, @function pushl movl pushl call addl subl leal pushl pushl call %ebp %esp, %ebp $.LC0 printf $16, %esp $8, %esp -4(%ebp), %eax %eax $.LC1 scanf Assembly language q Still missing definitions of printf() and scanf() 8

Results of Assembling q File circle.o: Listing omitted Not human-readable Machine language q Object file q Still missing definitions of printf() and scanf() The Linker s View q File circle.o: Listing omitted Not human-readable Machine language q The linker: q Observes that q Code in circle.o calls printf() and scanf() q Code in circle.o does not define printf() or scanf() q Fetches machine language definitions of printf() and scanf() from standard C library (/usr/lib/libc.a on your machine) q Merges those definitions with circle.o to create 9

Results of Linking q File circle: Listing omitted Not human-readable Machine language q Complete executable binary file Run-Time View q At run-time, memory devoted to program is divided into sections: TEXT RODATA DATA BSS HEAP STACK TEXT (read-only) Stores RODATA (read-only) Stores STACK (read/write) Stores Other sections described later in course 10

Run-Time View: Startup q At program startup: TEXT contains machine language code defining main(), printf(), scanf(), etc. TEXT STACK RODATA --- --- --- --- main printf scanf STACK is empty Enter the circle s radius\n\0 %d\0 RODATA contains every string constant used in program; each is an array of characters, terminated with the null character ( \0 ) A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Declarations int radius; int diam; double circum; TEXT STACK RODATA --- --- --- --- main printf scanf Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 11

Run-Time View: Writing a String printf("enter the circle's radius:\n"); TEXT STACK RODATA --- --- --- --- main printf scanf circum diam radius Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Reading an int scanf("%d", &radius); TEXT STACK RODATA --- --- --- --- main printf scanf circum diam radius 5 Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 12

Run-Time View: Computing Results diam = 2 * radius; circum = 3.14159 * (double)diam; TEXT STACK RODATA --- --- --- --- main printf scanf circum diam radius 5 Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Writing an int printf("a circle with radius %d has diameter %d\n", radius, diam); TEXT STACK RODATA --- --- --- --- main printf scanf circum diam radius 31.4159 10 5 Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 13

Run-Time View: Writing a double printf("and circumference %f.\n", circum); TEXT STACK RODATA --- --- --- --- main printf scanf circum diam radius 31.4159 10 5 Enter the circle s radius\n\0 %d\0 A circle with radius %d has diameter %d\n\0 and circumference %f.\n\0 Run-Time View: Exiting return 0; 14

What Goes Where? int fact(n) int i, result=1; for(i = 1; i<=n; i++) result = result * i; return result; int main() int n; printf( Enter a value\n ); scanf( %d, &n); printf( The factorial of %d is %d, n, fact(n)); return 0; What Goes Where? int fact(n) int i, ret=1; for(i = 1; i<=n; i++) ret = ret * i; return ret; TEXT STACK RODATA int main() int n; printf( Enter a value\n ); scanf( %d, &n); printf( The factorial of %d is %d, n,fact(n)); return 0; 15

Circle Program q File circle.c: #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = 3.14159 * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Toward Version 2 q Problem (stylistic flaw): q 3.14159 is a magic number q Should give it a symbolic name to q Increase code clarity q q Solution: Thereby increase code maintainability q (In Java: final fields, final variables) q In C: three approaches 16

Symbolic Constants: #define q Approach 1: #define void f(void) #define START_STATE 0 #define POSSIBLE_COMMENT_STATE 1 #define COMMENT_STATE 2... int state;... state = START_STATE;... state = COMMENT_STATE;... Symbolic Constants: #define q Approach 1 strengths q Preprocessor does substitutions only for tokens int mystart_state; /* No replacement */ q Preprocessor does not do substitutions within string constants printf("what is the START_STATE?\n"); /* No replacement */ q Simple textual replacement; works for any type of data #define PI 3.14159 17

Version 2 using #define #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Symbolic Constants: #define q Approach 1 weaknesses Preprocessor does not respect context Preprocessor does not respect scope void f(void) #define MAX 1000 int MAX = 2000; void f(void) #define MAX 1000 void g(void) int MAX = 2000; Conventions: Use all uppercase for constants -- and only for constants Place #defines at beginning of file, not within function definitions 18

Symbolic Constants: const q Approach 2: constant variables (oxymoron) void f(void) const int START_STATE = 0; const int POSSIBLE_COMMENT_STATE = 1; const int COMMENT_STATE = 2;...... int state;... state = START_STATE;... state = COMMENT_STATE;... Version 2 using const #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; 19

Symbolic Constants: const q Approach 2 strengths q Works for any type of data const double PI = 3.14159; q Handled by compiler, not preprocessor; compiler respects context and scope q Approach 2 weaknesses q Does not work for array lengths (unlike C++) const int ARRAY_LENGTH = 10;... int a[array_length]; /* Compiletime error */ Symbolic Constants: enum q Approach 3: Enumerations void f(void) enum State START_STATE, POSSIBLE_COMMENT_STATE, COMMENT_STATE,...; enum State state;... state = START_STATE;... state = COMMENT_STATE;... 20

Symbolic Constants: enum q Approach 3 note q Enumerated constants are interchangeable with ints q START_STATE is the same as 0 q POSSIBLE_COMMENT_STATE is the same as 1 q Etc. state = 0; /* Can assign int to enum. */ i = START_STATE; /* Can assign enum to int. */ Symbolic Constants: enum q Approach 3 strengths q Can explicitly specify values for names enum State START_STATE = 5, POSSIBLE_COMMENT_STATE = 3, COMMENT_STATE = 4,...; q Can omit type name, thus effectively giving names to int literals enum MAX_VALUE = 9999;... int i = MAX_VALUE; q Works when specifying array lengths enum ARRAY_LENGTH = 10;... int a[array_length];... 21

Version 2 using enum #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0. */ int radius; int diam; double circum; printf("enter the circle's radius:\n"); scanf("%d", &radius); diam = 2 * radius; circum = * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Symbolic Constants: enum q Approach 3 weakness q Does not work for non-integral data types enum PI = 3.14159; /* Compiletime error */ 22

Symbolic Constant Style Rules q Summary of style rules: 1. Use enumerations to give symbolic names to integral constants 2. Use const variables to give symbolic names to non-integral constants 3. Use #define with all uppercase at beginning of file Toward Version 3 q Problem: q Program does not handle bad user input $ circle Enter the circle's radius: abc User enters a non-number. How can the program detect that? What should the program do? 23

Detecting Bad User Input q Solution Part 1: Detecting bad user input scanf("%d", &radius) q q scanf() returns number of values successfully read Solution: Reporting Failure to User q Solution Part 2: Reporting failure to the user Stream Default Binding stdin Purpose Normal input C Functions stdout stderr Normal output Abnormal output q To report failure to user, should write a message to stderr 24

Reporting Failure to OS q Solution Part 3: Reporting failure to the operating system Nature of Program Completion Status Code that Program Should Return to OS Successful 0 EXIT_SUCCESS (#defined in stdlib.h as 0) Unsuccessful EXIT_FAILURE (#defined in stdlib.h as???) q To generate status code x, program should: q Execute return x statement to return from main() function, or q Call exit(x) to abort program System-dependent; q Shell can examine status code on tanner, 1 q Note: q In main() function, return statement and exit() function have same effect q In other functions, they have different effects What is Wrong? #include <stdio.h> int main() int n; printf( Enter a value\n ); scanf( %d, &n); printf( The factorial of %d is %d, n,fact(n)); return EXIT_SUCCESS; q Compilation error: q EXIT_SUCCESS' undeclared (first use in this function) 25

Circle Program (Version 3) #include <stdio.h> int main(void) /* Read a circle's radius from stdin, and compute and write its diameter and circumference to stdout. Return 0 if successful. */ const double PI = 3.14159; int radius, diam; double circum; printf("enter the circle's radius:\n"); /* Read radius here */ diam = 2 * radius; circum = PI * (double)diam; printf("a circle with radius %d has diameter %d\n", radius, diam); printf("and circumference %f.\n", circum); return 0; Arrays in C 26

Array Declaration q The dimension must be a constant or a constant expression (needs to be determined at compile time) #define BUFFSIZE 256 #define MAXSIZE 12 int main() int size = 6; char buffer[buffersize]; // elegant declaration // constant integer dimension char buffer[256]; // NOT an elegant declaration // integer literal dimension int dice[buffsize / 2]; // constant integer expression // used for dimension float rollvalue[size]; // NOT valid - size is not a // constant Array Initialization #define MAX 5 int count[max] = 5, 7, 2, 4, 8; count 5 7 2 4 8 [0] [1] [2] [3] [4] q Providing too many initial values causes a compile-time error: int count[max] = 1,2,3,4,5,6; // ERROR q If the number of initial values listed is less than the capacity of the array, the remaining elements are automatically initialized to 0. Thus int count[5] = 2; is equivalent to int count[5] = 2,0,0,0,0; 27

Array Indices q Logically, valid indices for an array range from 0 to MAX-1, where MAX is the dimension of the array int A[6]; stands for A[0], A[1], A[2], A[3], A[4] and A[5] Logically, there is no A[6] q Memory A[0] A[1] A[2] A[3] A[4] A[5] Out-of-Bounds Array Indices q A common logical error in processing arrays is exceeding the valid index range: #define MAX 100 int somearray[max]; somearray[max] = 0; // will compile // but run time ERROR q What happens when a statement uses an array index that is out of bounds? int i; for(i = 0; i <= MAX; i++) somearray[i] = 0; No automatic checking of array indices at run time 28

Out-of-Bounds Array Indices q The memory location somearray[100] may : 1. Store a variable declared in your program that variable will be altered. Since there is no statement that directly assigns a value to that variable, this effect seems very mysterious when debugging. 2. Not be allocated for the use of your program. The result depends on the operating system you are using. q Most operating systems, such as Windows NT and Unix, will detect that a memory access violation has occurred and suspend or kill your program NO Aggregate Array Operations q Aggregate operations refer to operations on an array as a whole, as opposed to operations on individual array elements. #define MAX 100 int x[max]; int y[max]; q There are no aggregate operations on arrays: Assignment x = y; Error Comparison if (x == y) Error I/O printf( %d, x); Error Arithmetic: x = x + y; Error 29

Strings in C String Declarations q Unlike Java, there is no String data type in C q Strings in C are simply arrays of characters terminated with 0 (character \0 ) char some[10]; // need to specify max size // one way: char msg[6] = H, e, y,,, \0 ; // another way (last 2 places unused): char msg[8] = Hey ; // no \0 // or char msg[ ] = Hey ; // no \0 memory for 6 characters ( 5 plus the null char \0 ) automatically allocated 30

Memory Representation q char some[10]; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] q char msg[6] = H, e, y,,, \0 ; [0] [1] [2] [3] [4] [5] H e y 0 q char msg[8] = Hey ; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] H e y 0 q char msg[] = Hey ; [0] [1] [2] [3] [4] [5] H e y 0 Reading Into a String (1) #define MAX_BUFFER 20 char buffer[max_buffer]; scanf( %s, buffer); gets(buffer); // or q What if the array is not large enough to hold the input? q characters will be stored into memory locations past the end of the array q will result in run-time memory access violation error 31

Reading Into a String (2) q Better: #define MAX_BUFFER 20 char buffer[max_buffer]; fgets(buffer, MAX_BUFFER, stdin); q fgets is similar to gets, but: q it takes a third argument, in our case standard input q if stores into buffer no more than MAX_BUFFER chars (extra characters are ignored), so memory violation error won t occur Functions for Manipulating Strings q C provides a large number of functions for manipulating strings. Four important ones: strlen(s) // returns the length of s strcpy(tos, froms) // copy froms to tos (tos must be large enough) strcmp(s1, s2) // returns 0 if s1 == s2 // returns an integer < 0 if s1 < s2 // returns an integer > 0 if s1 > s2 strtok read the Unix manual pages to find out what this function does 32

String exercise q Write a function int length(char * s); that returns the length of the string argument. Examples: length( abc ) should return 3 length( abc\0 ) should return length( abc\\0 ) should return Pointers in C 33

What are Pointers? q A pointer is a variable that holds the ADDRESS of another variable q Suppose that we have an integer variable int i; and wish to have a pointer point to this variable. q How do we know where i is located? &i is the address of i. The operator & is called the ADDRESS-OF operator. Pointers and Addresses q We can declare that a pointer iptr points to an int by saying int * iptr; q Suppose that we have: int i = 5; int j = 7; (&i) 100 (&j) 180 260 5...... 7 100 i j iptr q We can make iptr point to i by assigning to iptr the memory location where i is stored. Thus iptr = &i; sets iptr to point to i. iptr i 5 34

Declaring Pointers q When declaring several pointer variables in one statement - the asterisk does not distribute throughout the statement: int *p, q; equivalent to int * p; int q; equivalent to int * p, * q; int * p; int * q; Initializing Pointers q We can also initialize iptr at the point of declaration: int i; int * iptr = &i; iptr i??? q Here is a common error: int i; int * iptr = i; // ERROR: i is not an address 35

Dereference * q The value of the data being pointed at is obtained by using the operator * q If p is a pointer value, then *p refers to the variable pointed to by p. Since reference is another name for address, the operator * is called dereference operator. Dereference Example int i; int * p = &i; *p = 101; (*p)++; i??? p i??? p i 101 p i 102 Equivalent to i = 101; Equivalent to i++; q A dereferenced pointer behaves exactly like the variable it points to. 36

Note the Difference Assume: ptr1 i 5 ptr1 ptr2 i j 5 7 After ptr1 = ptr2; ptr2 j 7 ptr1 i 7 After ptr2 j 7 *ptr1 = *ptr2; Uninitialized Pointers q Suppose that we have the following declarations: int i; int * iptr; *iptr = 100; iptr q What is the value of iptr? Undefined. What could happen? q iptr could hold an address that does not make sense at all, causing your program to crash if dereferenced. i??? q iptr could point to an address which is accessible. Then the assignment *iptr = 100; would accidentally change some other data, which could result in a crash at a later point. This is a tough error to detect since the cause and symptom may be widely separated in time. 37

Putting it all Together... int i, value; int * iptr; // declares iptr to be a pointer to an integer i = 510; /* Step 1 */ iptr = &i; /* Step 2 */ value = *iptr; /* Step 3 */ iptr i value After Step1: After Step2: iptr i value After Step3: iptr i value The null Pointer q The value of a pointer can be: q some garbage (pointer unassigned) q the address of some variable (eg., int * p = &i; ) q the constant 0 (the null pointer, points to absolutely nothing) somepointer = 0; This statement does not cause somepointer to point to memory location zero; it guarantees that somepointer does not point to anything. q The null pointer is a special pointer value that a program can test for: if (somepointer == 0)... 38

Arrays vs. Pointers Arrays and Pointers - Examples q Consider the following declarations: int a[5] = 1, 2, 3; a 1 2 3?? int * p; p p = &a[2]; a 1 2 3?? p q You can use the index [] operator with a pointer: p[0] = 17; p[1] = 23; a 1 2 17 23? Indexing can be used with any pointer, but it only makes sense when the pointer points to an array. p 39

Arrays are NOT Pointers q Declaring an array sets aside space for its elements char a[5]; a a[0] a[1] a[2] a[3] a[4] q Declaring a pointer variable sets aside only space to hold the variable char * p; p q You can change a pointer variable, but not the address of an array char b[6]; p = b; // OK p b = p; // ERROR b b[0] b[1] b[2] b[3] b[4] b[5] Indexing Pointers int a[5]; int *p, *q; p a 44 217 45 44 43 p = a; p[1]= 44; q 226 46 q = p + 2; q[-1] = 43; q[2] = 46; 40

Pointer Arithmetic int a[5]; p a 217 226 Subscript: a[i] means *(a+i) int *p; 4 bytes p = a + 2; Note: arithmetic scales by data size (e.g., int of 4 bytes) Quaint usage of pointer arithmetic Add up the elements of an array: More straightforwardly: int a[100]; int sum, *p; int a[100];... int sum, i; for (p=a; p<a+100; p++)... sum += *p; for (i=0; i<100; i++) sum += a[i]; 41

Array Parameters to Functions void printarray(int *p, int n) int i; for (i=0; i<n; i++) printf( %d\n,p[i]); int fib[5] = 1, 1, 2, 3, 5; int main(void) printarray(fib, 5); Array Params Pointer Params void printarray(int *p, int n)... void printarray(int p[5], int n)... void printarray(int p[ ], int n)... void printarray(int p[1000], int n)... int main(void) printarray(fib, 5); All these declarations are equivalent Try them out. 42

Exercise: Reverse Array q Reverse the values in an array q Inputs: integer array a, and number of elements n q Output: values of a stored in reverse order q Algorithm q Swap the first and last elements in the array q Swap the second and second-to-last elements q 77 31 94 5 186 Exercise: length using pointers q Rewrite the function int length(char * s); using pointers, instead of array indices. Examples: length( abc ) should return 3 length( abc\0 ) should return length( abc\\0 ) should return 43

Swapping two values q Write a function void swap(int first, int second); that swaps the values of its arguments. Example: int i1 = 11, i2 = 22; printf( Before: i1=%d, i2=%d\n, i1, i2); swap(i1, i2); printf( After: i1=%d, i2=%d\n, i1, i2); Output should be: Before: i1=11, i2=22 After: i1=22, i2=11 Can t do it? q Try the correct version void swap(int *first, int *second); that swaps the values of its arguments. Example: int i1 = 11, i2 = 22; printf( Before: i1=%d, i2=%d\n, i1, i2); swap(&i1, &i2); printf( After: i1=%d, i2=%d\n, i1, i2); Output should be: Before: i1=11, i2=22 After: i1=22, i2=11 44

Summary q Simple C programs q Program structure q Detecting and reporting failure q Functionality of the gcc command q Preprocessor, compiler, assembler, linker q Memory layout of a Unix process q TEXT, RODATA, STACK sections q Input/Output in C q printf, scanf, fprintf, getchar, putchar, gets, fgets q Arrays, Strings and Pointers in C 45