Week 5 - Monday CS222.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7: User-Defined Functions II
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Week 5 - Wednesday.  What did we talk about last time?  Arrays.
Kernighan/Ritchie: Kelley/Pohl:
(1) ICS 313: Programming Language Theory Chapter 10: Implementing Subprograms.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Week 4 - Wednesday.  What did we talk about last time?  Evil: break, continue, goto  System calls  Functions.
1 Further C  Multiple source code file projects  Structs  The preprocessor  Pointers.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Copyright 2001 Oxford Consulting, Ltd1 January Storage Classes, Scope and Linkage Overview Focus is on the structure of a C++ program with –Multiple.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
1 Homework / Exam Finish up K&R Chapters 3 & 4 Starting K&R Chapter 5 Next Class HW4 due next class Go over HW3 solutions.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
Week 4 - Friday.  What did we talk about last time?  Some extra systems programming stuff  Scope.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Week 5 - Monday.  What did we talk about last time?  Processes  Lab 4.
Recursion ● Recursion is a computer programming technique that allows programmers to divide problems into smaller problems of the same type. ● You can.
Lecture 3 Translation.
Computer Organization and Design Pointers, Arrays and Strings in C
Test 2 Review Outline.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Week 4 - Friday CS222.
Prof: Dr. Shu-Ching Chen TA: Samira Pouyanfar Spring 2017
CSE 374 Programming Concepts & Tools
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Lecture 7 Arrays, Dynamic Arrays & Copy Constructors “Absolute C++”
C Programming Tutorial – Part I
COSC 220 Computer Science II
Numeric Arrays Numeric Arrays Chapter 4.
Java Review: Reference Types
Week 4 - Monday CS222.
Programmazione I a.a. 2017/2018.
Arrays in C.
Instructor: Ioannis A. Vetsikas
Object Oriented Programming COP3330 / CGS5409
7 Arrays.
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Memory Allocation CS 217.
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
Defining methods and more arrays
Object Oriented Programming in java
Variables Title slide variables.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers and Arrays Beyond Chapter 16
7 Arrays.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Object Oriented Programming in java
Submitted By : Veenu Saini Lecturer (IT)
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Compiler vs linker The compiler translates one .c file into a .o file
SPL – PS1 Introduction to C++.
Week 2 - Friday CS222.
Week 7 - Friday CS222.
SPL – PS2 C++ Memory Handling.
Week 7 - Monday CS 121.
Week 9 - Monday CS222.
Week 5 - Wednesday CS222.
Presentation transcript:

Week 5 - Monday CS222

Last time What did we talk about last time? Processes Scope Lab 4

Questions?

Project 2

Quotes A C program is like a fast dance on a newly waxed dance floor by people carrying razors. Waldi Ravens

extern declarations What if you want to use a global variable declared in another file? No problem, just put extern before the variable declaration in your file There should only be one true declaration, but there can be many extern declarations referencing it Function prototypes are implicitly extern file2.c int count; extern int count; file1.c file3.c program.c

static declarations The static keyword causes confusion in Java because it means a couple of different (but related) things In C, the static keyword is used differently, but also for two confusing things Global static declarations Local static declarations

Global static variables When the static modifier is applied to a global variable, that variable cannot be accessed in other files A global static variable cannot be referred to as an extern in some other file If multiple files use the same global variable, each variable must be static or an extern referring to a single real variable Otherwise, the linker will complain that it's got variables with the same name

Local static variables You can also declare a static variable local to a function These variables exist for the lifetime of the program, but are only visible inside the method Some people use these for bizarre tricks in recursive functions Try not to use them! Like all global variables, they make code harder to reason about They are not thread safe

Local static example #include <stdio.h> void unexpected() { static int count = 0; count++; printf("Count: %d", count); } int main() unexpected(); //Count: 1 unexpected(); //Count: 2 unexpected(); //Count: 3 return 0;

The register modifier register int value; You can also use the register keyword when declaring a local variable It is a sign to the compiler that you think this variable will be used a lot and should be kept in a register It's only a suggestion You can not use the reference operator (which we haven't talked about yet) to retrieve the address of a register variable Modern compilers are better at register allocation than humans usually are register int value;

Arrays

Declaration of an array To declare an array of a specified type with a given name and a given size: Example with a list of type int: type name[ size ]; int list[ 100 ];

Differences from Java When you declare an array, you are creating the whole array There is no second instantiation step It is possible to create dynamic arrays using pointers and malloc(), but we haven't talked about it yet You must give a fixed size (literal integer or a #define constant) for the array These arrays sit on the stack in C Creating them is fast, but inflexible You have to guess the maximum amount of space you'll need ahead of time

Accessing elements of an array You can access an element of an array by indexing into it, using square brackets and a number Once you have indexed into an array, that variable behaves exactly like any other variable of that type You can read values from it and store values into it Indexing starts at 0 and stops at 1 less than the length Just like Java list[9] = 142; printf("%d", list[9]);

Length of an array The length of the array must be known at compile time Our version of gcc has looser rules about this, but C90 insists on true constants There is no length member or length() method It is possible to find out how many bytes a statically allocated array uses with sizeof But you can only be sure that works in the function where the array is defined! int list[100]; int size = sizeof(list); //400 int length = size/sizeof(int); //100

Arrays start filled with garbage When you create an array, it is not automatically filled with any particular value Inside the array (like any variable in C) is garbage With regular variables, you might get a warning if you use a variable before you initialize it With an array, you won't

Explicit initialization Explicit initialization can be done with a list: You can omit the size if you use an explicit initialization because the compiler can figure it out int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; char grades[] = { 'A', 'B', 'C', 'D', 'F'};

memset() The C standard library has a function called memset() that can set all the bytes in a chunk of memory to a particular value Using it is guaranteed to be no slower than using a loop to initialize all the values in your array It usually uses special instructions to set big chunks of memory at the same time int values[100]; memset(values, 0, sizeof(int)*100); //zeroes out array char letters[26]; memset(letters, 'A', sizeof(char)*26); //sets array to all 'A's

memcpy() memset() is mostly useful for initialization (and usually only for zeroing things out) memcpy() is a fast way to copy values from one array to another Again, it's at least as fast as using your own loop Again, it's somewhat dangerous since it lets you write memory places en masse int cubes[100]; int copy[100]; int i = 0; for( i = 0; i < 100; i++) cubes[i] = i*i*i; memcpy(copy, cubes, sizeof(cubes));

Passing arrays to functions Using an array in a function where it wasn't created is a little different You have to pass in the length The function receiving the array has no other way to know what the length is sizeof will not work because it is based on what is known at compile time The function should list an array parameter with empty square brackets on the right of the variable No brackets should be used on the argument when the function is called Like Java, arguments are passed by value, but the contents of the array are passed by reference Changes made to an array in a function are seen by the caller

Array to function example Calling code: int values[100]; int i = 0; for( i = 0; i < 100; i++ ) values[i] = i + 1; reverse(values, 100);

Array to function example void reverse(int array[], int length) { int start = 0; int end = length – 1; int temp = 0; while( start < end ) temp = array[start]; array[start++] = array[end]; array[end--] = temp; }

Returning arrays In C, you can't return the kind of arrays we're talking about Why? They are allocated on the stack When a function returns, all its memory disappears If you dynamically allocate an array with malloc(), you can return a pointer to it

Array Memory

Memory An array takes up the size of each element times the length of the array Each array starts at some point in computer memory The index used for the array is actually an offset from that starting point That’s why the first element is at index 0

A look at memory We can imagine that we have an array of type int of length 10 Let’s say the array starts at address 524 Addresses 12 43 -9 6 789 -23 23 10 0 1 2 3 4 5 6 7 8 9 524 528 532 536 540 544 548 552 556 560 Indexes

Multidimensional arrays It is legal to declare multidimensional arrays in C They'll work just as you would expect Except! You have to give the second dimension when passing to a function (otherwise, it won't know how big of a step to take when going from row to row) char board[8][8]; void clearBoard( char board[][8]) { int i = 0; int j = 0; for( i = 0; i < 8; i++ ) for( j = 0; j < 8; j++ ) board[i][j] = ' '; }

Array example Write a program that reads an integer from the user saying how many values will be in a list Assume no more than 100 If the user enters a value larger than 100, tell them to try a smaller value Read these values into an array Find Maximum Minimum Mean Variance Median Mode

Review of Compiling Multiple Files

Components C files Header files Makefile All the sources files that contain executable code Should end with .c Header files Files containing extern declarations and function prototypes Should end with .h Makefile File used by Unix make utility Should be named either makefile or Makefile

C files You can have any number of .c files forming a program Only one of them should have a main() function If the functions in a .c file will be used in other files, you should have a corresponding .h file with all the prototypes for those functions whatever.c should have a matching whatever.h Both the .c file that defines the functions and any that use them should include the header

Header files Sometimes header files include other header files For this reason, it is wise to use conditional compilation directives to avoid multiple inclusion of the contents of a header file For a header file called wombat.h, one convention is the following: #ifndef WOMBAT_H #define WOMBAT_H //maybe some #includes of other headers //lots of function prototypes #endif

Compiling When compiling multiple files, you can do it all on one line: Alternatively, you can compile files individually and then link them together at the end gcc main.c utility.c wombat.c –o program gcc –c main.c gcc –c utility.c gcc –c wombat.c gcc main.o utility.o wombat.o –o program

Makefile Compiling files separately is more efficient if you are only changing one or two of them But it's a pain to type the commands that recompile only the updated files That's why makefiles were invented program: main.o utility.o wombat.o gcc main.o utility.o wombat.o –o program main.o: main.c utility.h wombat.h gcc –c main.c utility.o: utility.c utility.h gcc –c utility.c wombat.o: wombat.c wombat.h gcc –c wombat.c clean: rm –f *.o program

Upcoming

Next time… Strings

Reminders Keep reading K&R chapter 5 Keep working on Project 2 Due Friday Exam 1 next Monday