Week 5 - Monday.  What did we talk about last time?  Processes  Lab 4.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Chapter 7: User-Defined Functions II
Week 5 - Wednesday.  What did we talk about last time?  Arrays.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
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.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
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.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
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.
Pointers Applications
 CS105 C++ Lecture 2 Arrays. Parameter passing  2 types  Pass-by-value  Pass-by-reference 2.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 Further C  Multiple source code file projects  Structs  The preprocessor  Pointers.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2006 Pearson Education, Inc. All rights reserved Arrays.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Microsoft Visual C++.NET Chapter 61 Memory Management.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
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.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Stack and Heap Memory Stack resident variables include:
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
Week 9 - Monday.  What did we talk about last time?  Time  GDB.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CSC Programming for Science Lecture 34: Dynamic Pointers.
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
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.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Week 5 - Monday CS222.
COSC 220 Computer Science II
Java Review: Reference Types
7 Arrays.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers and Arrays Beyond Chapter 16
7 Arrays.
SPL – PS2 C++ Memory Handling.
Week 7 - Monday CS 121.
Week 9 - Monday CS222.
Week 5 - Wednesday CS222.
Presentation transcript:

Week 5 - Monday

 What did we talk about last time?  Processes  Lab 4

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

 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 ];

 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

 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]); list[9] = 142; printf("%d", list[9]);

 The length of the array must be known at compile time  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 do that in the function where the array is defined! int list[100]; int size = sizeof(list); //400 int length = size/sizeof(int); //100 int list[100]; int size = sizeof(list); //400 int length = size/sizeof(int); //100

 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 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'};

 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 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

 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)); 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));

 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

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

 Function: 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; } 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; }

 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

 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

 We can imagine that we have an array of type int of length 10  Let’s say the array starts at address Addresses Indexes

 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] = ' '; } 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] = ' '; }

 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

 C files  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

 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

 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 #ifndef WOMBAT_H #define WOMBAT_H //maybe some #includes of other headers //lots of function prototypes #endif

 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 gcc –c main.c gcc –c utility.c gcc –c wombat.c gcc main.o utility.o wombat.o –o program

 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 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

 Strings

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