Discussion 3 Richard Guo Advanced C 01/28/09

Similar documents
Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Discussion 4 Richard Guo SLAB, Buddy, Garbage Collection, and Intro to MIPS 01/30/09

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Procedures, Parameters, Values and Variables. Steven R. Bagley

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Memory Management. CSC215 Lecture

DEPARTMENT OF MATHS, MJ COLLEGE

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

AMCAT Automata Coding Sample Questions And Answers

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Chapter 1 & 2 Introduction to C Language

Fundamental of Programming (C)

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

Fundamental of Programming (C)

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Data types, variables, constants

Kurt Schmidt. October 30, 2018

C: How to Program. Week /Mar/05

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

CS16 Exam #1 7/17/ Minutes 100 Points total

CS 241 Data Organization Pointers and Arrays

CS16 Midterm Exam 1 E01, 10S, Phill Conrad, UC Santa Barbara Wednesday, 04/21/2010, 1pm-1:50pm

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

High Performance Computing in C and C++

Chapter 2 - Introduction to C Programming

Lecture 02 C FUNDAMENTALS

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

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

First of all, it is a variable, just like other variables you studied

CA341 - Comparative Programming Languages

Roadmap. Java: Assembly language: OS: Machine code: Computer system:

CSE 351: The Hardware/Software Interface. Section 2 Integer representations, two s complement, and bitwise operators

CSE 230 Intermediate Programming in C and C++

Dynamic memory allocation

Syntax and Variables

A Fast Review of C Essentials Part I

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

Review of the C Programming Language for Principles of Operating Systems

Fundamentals of Programming

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

CS 11 C track: lecture 5

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

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Contents of Lecture 3

Computer Organization & Systems Exam I Example Questions

ANSI C Programming Simple Programs

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

OBJECT ORIENTED PROGRAMMING USING C++

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Data Representation and Storage. Some definitions (in C)

Section Notes - Week 1 (9/17)

Understanding Pointers

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

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

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

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

COMP 2355 Introduction to Systems Programming

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

CS3157: Advanced Programming. Announcement

EL6483: Brief Overview of C Programming Language

EL2310 Scientific Programming

INTRODUCTION 1 AND REVIEW

Memory Corruption 101 From Primitives to Exploit

DS Assignment II. Full Sized Image

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

211: Computer Architecture Summer 2016

Review of the C Programming Language

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Pointers and Arrays 1

Approximately a Test II CPSC 206

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Programming. Structures, enums and unions

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts

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

Lecture 03 Bits, Bytes and Data Types

Arrays and Pointers in C. Alan L. Cox

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

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

C Programming Review CSC 4320/6320

BLM2031 Structured Programming. Zeyneb KURT

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Pointers. Introduction

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

My malloc: mylloc and mhysa. Johan Montelius HT2016

CS 61c: Great Ideas in Computer Architecture

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

Basic Types, Variables, Literals, Constants

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

CS 237 Meeting 19 10/24/12

Heap Arrays. Steven R. Bagley

Transcription:

Discussion 3 Richard Guo Advanced C 01/28/09 1. Answers to Last Time's Problems 1. #include <stdlib.h> int increment (int ptr); int ptr; // will not actually get used b/c masked by local variables with same name void main () // main doesn't have to return anything. valid. int *ptr = (int *) malloc (sizeof(int)); // valid. Will mask global variable // sizeof should be int* (logic error), but fine b/c int* = int = 4 bytes ptr = &ptr; // sets the ptr to point to itself. Not an error but still weird for (int a = 0; a < 1; a++) // creation of int here is invalid (syntax error) *(ptr--) = increment(&ptr); // (logic error) decrements ptr's value return; // return by itself without anything exits the funtion. valid int increment (int ptr); // (syntax error) cannot have a semicolon here return ptr++; // again, reusing variable name is bad form but still valid. 2. int width=0, i; scanf ("%d", &width); // you should check whether you got valid input matrix = (int *)malloc(width*width*sizeof(int)); printf ("%d ", matrix[i]); // doesn't factor in nice spacing if ((i+1) % width == 0) printf ("\n"); 3. int width=0, i, x, y, avg; scanf ("%d", &width); // you should check whether you got valid input matrix = (int *) malloc(width*width*sizeof(int));

if (i % width!= 0 && i % width!= width-1 && i > width && i < width*width-width) // not on edges avg = 0; for (x = -1; x < 1; x++) for (y = -1; y < 1; y++) avg += matrix[i+y*width+x]; avg /= 9; printf ("%d ", i); // doesn't factor in nice spacing if ((i+1) % (width) == width-1) // if on the end of the row printf ("\n"); // output a newline 4. #include <stdlib.h> int main(int argc, char** argv) int width=0, i; if (argc == 2) width = atoi(argv[1]); matrix = (int *)malloc(width*width*sizeof(int)); printf ("%d ", matrix[i]); // doesn't factor in nice spacing if ((i+1) % width == 0) printf ("\n"); 2. Array of Arrays Method 1 (simple to code but harder to access) int width, height; int *array; // fill in width, height via scanf, etc. array=malloc(width*height*sizeof(int)); array[width*x+y] // to access x, y free(array); // free up memory Method 2 (easier to access, but more complex code) int width, height; int **array; // fill in width, height via scanf, etc. array=malloc(width*sizeof(int*)); for (a = 0; a < width; a++) array[a]= malloc(height*sizeof(int)); array[x][y] // access position x, y for (a = 0; a < width; a++) free(array[a]); // free each column free(array); // free width

3. I/O Operations We've seen printf in the first discussion. You've used scanf in lab. Now we introduce to you sprintf. It follows the printf notation but stores the output sting in a variable instead of printing to the terminal. sprintf (char* destination_string, const char * format,...); char *temp; printf ( %d + %d = %d, x, y, x) // print to screen sprintf (*temp, %d + %d = %d, x, y, x) // puts the same string into temp There is also a command called fprintf that outputs to a local file. 5. Struct, Union, and Typedef Command Function Example typedef type1 type2 type2 var2; struct typename type1 member1; type2 member2; ; typename varname; union typename type1 member1; type2 member2; ; typename varname; enum enumname NAME1 = 1, NAME2 = 3; // setting equal to a number is optional. If not done, numbers are sequential Substitutes variable type type1 for type2 whenever type2 is seen in your code. Groups multiple variable types under one. Similar to classes in storing public variables but different in that struct doesn't allow methods. Structures use memory <= the combined sizes of its members. Similar to structure, but memory is shared and enough is allocated for the largest type. This means only one of its members can be used at a time. Allows renaming of numbers as something more legible. So, instead of testing whether a variable == 1, 2,... we can test whether it equals ERROR_SEG, ERROR_BUS,... string blurb = blah ; struct person ; // outside main person me; // inside main me.name = Richard ; me.age = 20; union numbers int a; float b; char c; ; // outside main numbers my_numbers; my_numbers.a = 1; my_numbers.b = 0.1234; // a is overwritten by b enum suits CLUBS, DIAMONDS, HEARTS, SPADES; enum suits hand; //in main hand = HEARTS; hand = 2; // same as above

The code on the left returns an error while the code on the right works. Why? struct person ; person * new_person = (person*)malloc(sizeof(person)); return 0 typedef struct person person_var; person_var * new_person = (person_var*)malloc(sizeof(person_var)); return 0; C is lazy/stupid. It does not recognize person as a new data type. The typedef statement defines person_var as a data type that can be used just like int, char, float, etc. 6. More Fun With Memory Uh-oh... Fragmentation Memory that is freed up in the middle of program execution causes fragmentation because memory is now noncontiguous. When malloc is called to find available memory, it can use various algorithms: Best First Next Scans all free chunks of memory. Returns the smallest contiguous section that is bigger than or equal to the requested amount of memory. Slow but guarantees most efficient use of memory. Scans from the beginning and returns the address of free memory first encountered that is >= to requested amount. Very fast but possibly inefficient. Same as first fit except that instead of starting at the beginning of memory space, remember where the last malloc finished and start from there. Simple way of being relatively balanced.

7. Solved Problems Bitwise operator problem write a program to simulate a 32 bit barrel shifter. That is, prompt for the number of bits to shift (positive = to the right, negative = to the left). Then rotate the number by that many bits. E.g. an 8 bit number 11010011 shifted to the right by 3 bits would give 01111010. unsigned int number=0, overflow_mask=0, overflow=0; int shift=0; scanf ("%d", &number); // you should check whether you got valid input printf ("\nhow much do you want to shift by? "); scanf ("%d", &shift); // you should check whether you got valid input if (shift < 0) // shift left shift *= -1; // make amount of shift positive overflow_mask = 0xFFFFFFFF << (32 shift); // generate mask overflow_mask = overflow_mask & number; // copy masked bits in number overflow_mask = overflow_mask >> (32 shift); // shift mask down number = number << shift; // rotate number else if (shift > 0) // shift right overflow_mask = 0xFFFFFFFF >> (32 shift); // generate mask overflow_mask = overflow_mask & number; // copy masked bits in number overflow_mask = overflow_mask << (32 shift); // shift mask up number = number >> shift; // rotate number number = number overflow; // paste masked bits back into zeros in number printf("%u\n", number); // output 8. More Problems (solutions will be on *next* discussion's handout) 1. Write a program to create a linked list a data type where each node stores a value and points to the next node in the list.