Lectures 5-6: Introduction to C

Similar documents
Lectures 5-6: Introduction to C

Chapter IV Introduction to C for Java programmers

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

PRINCIPLES OF OPERATING SYSTEMS

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

CSCI 171 Chapter Outlines

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

Lecture 3: C Programm

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Kurt Schmidt. October 30, 2018

CMPE-013/L. Introduction to C Programming

CS 61C: Great Ideas in Computer Architecture Introduction to C

Lecture 2: C Programm

Programming refresher and intro to C programming

CS201 - Introduction to Programming Glossary By

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

C programming basics T3-1 -

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

Arrays and Pointers (part 1)

Short Notes of CS201

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

Motivation was to facilitate development of systems software, especially OS development.

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

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

CS 61c: Great Ideas in Computer Architecture

Arrays and Pointers (part 1)

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

Pointers, Dynamic Data, and Reference Types

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

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

EL6483: Brief Overview of C Programming Language

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

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

EL2310 Scientific Programming

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

Motivation was to facilitate development of systems software, especially OS development.

[0569] p 0318 garbage

C Programming Review CSC 4320/6320

Procedural programming with C

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

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

Software Project. Lecturers: Ran Caneti, Gideon Dror Teaching assistants: Nathan Manor, Ben Riva

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

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

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

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

Topic 6: A Quick Intro To C

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

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

TDDB68 Concurrent Programming and Operating Systems. Lecture 2: Introduction to C programming

PERIYAR CENTENARY POLYTECHNIC COLLEGE Periyar Nagar- Vallam Thanjavur

Class Information ANNOUCEMENTS

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

A software view. Computer Systems. The Compilation system. How it works. 1. Preprocesser. 1. Preprocessor (cpp)

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

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

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

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

edunepal_info

A brief introduction to C programming for Java programmers

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

MODULE 5: Pointers, Preprocessor Directives and Data Structures

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

ECEN 449 Microprocessor System Design. Review of C Programming

Arrays and Pointers in C. Alan L. Cox

A Fast Review of C Essentials Part I

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Fundamentals of Programming

Lecture 2: C Programming Basic

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

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Programming in C - Part 2

CS349/SE382 A1 C Programming Tutorial

211: Computer Architecture Summer 2016

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

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Lecture 03 Bits, Bytes and Data Types

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Model Viva Questions for Programming in C lab

Compiling and Running a C Program in Unix

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Informatica e Sistemi in Tempo Reale

BLM2031 Structured Programming. Zeyneb KURT

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

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

For instance, we can declare an array of five ints like this: int numbers[5];

COMP322 - Introduction to C++

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

Fundamental of Programming (C)

High Performance Computing Lecture 1. Matthew Jacob Indian Institute of Science

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

Computer Systems Lecture 9

ELEC 377 C Programming Tutorial. ELEC Operating Systems

EC 413 Computer Organization

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Transcription:

Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most of the syntax is the same Most statements, expressions are the same Inf2C Computer Systems 2010-2011 1

Outline Major differences with Java A simple program; how to compile and run Data-types and variables The preprocessor Composite data structures Arrays and strings Pointers Inf2C Computer Systems 2010-2011 2

Major differences with Java C is not object oriented C programs are collections of functions, like Java methods, but not class-based. No inheritance, subtyping, dynamic dispatch in C C is not interpreted A C program is compiled into an executable machine code program, which runs directly on the processor Java programs are compiled into a byte code, which is read and executed by the Java interpreter, another program Inf2C Computer Systems 2010-2011 3

C is less safe Run-time errors are not caught in C The Java interpreter catches these errors before they are executed by the processor C run-time errors happen for real and the program crashes The C compiler trusts the programmer! Many mistakes go un-noticed, causing run-time errors Inf2C Computer Systems 2010-2011 4

Memory management is different Memory areas Heap: dynamically allocated storage Stack: for function/method local variables Static: for data living program lifetime In Java All objects on heap Unusable objects on heap recycled automatically by garbage collection In C Data structures in all 3 areas Programs must explicitly free-up heap storage that is no longer needed Inf2C Computer Systems 2010-2011 5

C has pointers Pointers are special variables that reference (or point to) another variable Similar to Java references We have already seen pointers in assembly: lw $t1,0($s2) $s2is a pointer C pointers are the same thing! (more later) Inf2C Computer Systems 2010-2011 6

The hello world program #include<stdio.h> /* This is a (multi-line) comment */ int main(void) { // This is a comment too printf("hello world!\n"); return 0; } Linux/DICE shell commands Compile: gcc hello.c Run:./a.out Inf2C Computer Systems 2010-2011 7

Compilation units Programs are divided into compilation units Provide degree of modularity Each commonly has main file for source code Header files characterise public interfaces of units Each compiled separately to relocatable object code Allows creation of object-code libraries A linker assembles these into an executable, resolving references between units A loader sets up the executable program in memory and initialises data areas, prior to program being run Inf2C Computer Systems 2010-2011 8

Compilation units example A.h: func decls var decls type defs A.c: #include "A.h" func defs var defs B.h: func decls var decls type defs B.c: #include <stdio.h> #include "A.h" #include "B.h" func defs var defs Inf2C Computer Systems 2010-2011 9

Built-in data types The usual basic data types are there: char 8 bits short 16 int 16, 32, 64 (same as machine word size) long 32, 64 float 32 Bit sizes are machine dependent Unlike Java where an int is always 32 bits Normally signed, unsigned available too No boolean type exists for any number (int, char, ): 0 false, other true Inf2C Computer Systems 2010-2011 10

Categories of variables Global (external) variables (statically allocated) Defined outside of functions Have lifetime of program and scope to file end extern declarations extend scope before definition and to other files Declare static to hide from other files Local (automatic) variables (allocated on stack) Defined inside a function (before the statements) Not available outside function Distinct storage for each function invocation Declare static for same storage for all invocations Inf2C Computer Systems 2010-2011 11

The C pre-processor: cpp Includes imports header files Declarations for variables, functions, Text substitution, e.g. define constants #define NAME value Macros (inline functions) #define MAX(X,Y) (X>Y? X:Y) Conditional compilation #ifdef DEBUG printf( Debugging message ) #endif Inf2C Computer Systems 2010-2011 12

Composite data structures - struct Structures objects without methods: struct point { int x, y; } p1; struct point p2; To access a structure component, use the struct member operator. p1.x = 2; Passing structures between functions In Java references always used In C either all data copied or pointers used Inf2C Computer Systems 2010-2011 13

Composite data structures - union Unions declared and used similarly to structures: union geomobject { struct circle; struct rectangle; } g_obj; But all variables inside a union overlap in memory, Space is reserved for the largest of them, not all The same memory space can be interpreted in multiple ways Inf2C Computer Systems 2010-2011 14

In memory: structures v. unions struct x{ int var1; int var2; } sx; union x{ int var1; int var2; } ux; var1 var2 sx var1/var2 ux sizeof(sx) 8 sizeof(ux) 4 Inf2C Computer Systems 2010-2011 15

User-defined types Define names for new or built-in types typedef <type> <name>; Example: typedef unsigned char byte; typedef struct { struct point p; int rad; } circle;... circle c1, c2; Inf2C Computer Systems 2010-2011 16

Arrays Syntax of C arrays similar to Java As in Java, C arrays have fixed size Example declarations of array: int n[] = {5, 8, 10}; // size fixed to 3 circle c[4]; // array of structs C arrays have no knowledge of their length No checking that indexes are within bounds In C is close relationship between arrays and pointers Pointers commonly used to pass arrays between functions Inf2C Computer Systems 2010-2011 17

Strings C strings are simply arrays of type char Encoded in 8bits using ASCII They end with '\0', the null character char s[10]; // up to 9 characters long String initialisation char s[10] = string ; // '\0 implied Char s1[] = another string ; Usual C rule for arrays apply: Cannot store more chars than reserved at declaration But bounds are not checked! Inf2C Computer Systems 2010-2011 18

Strings common operations Assignment: strcpy(s, string ); Length: strlen(s) To get the 6 th character: s[5] First char at position 0, as in Java arrays Comparison, strcmp(s1, s2) returns: 0 when equal Negative number when lexicographically s1 < s2 Positive when s1>s2 Must #include<string.h> to call the functions Type: man string to see what s available Inf2C Computer Systems 2010-2011 19

Pointers We have seen pointers in assembly: lw $t1,0($s2) $s2 points to the location in memory where the real data is kept $s2 is a register, but there s nothing stopping us to have pointers stored in memory like normal variables Address 0x104 0x100 data 0x100 reg $s2 0x100 Inf2C Computer Systems 2010-2011 20

C pointers A C pointer is a variable that holds the address of a piece of data Declaration: int *p; // p is a pointer to an int The compiler must know what data type the pointer points to Basic pointer usage: p = &i; // p points to i now *p = 5; // *p is another name for i & - address of, * dereference operator Inf2C Computer Systems 2010-2011 21

Pointers as function arguments In C (and Java, for primitive types) function arguments are passed by value Function gets own copy of the arguments values How could then a function modify the original argument variables? Pass pointers to the variables Inf2C Computer Systems 2010-2011 22

Example the swap function void swap_wrong(int a, int b) { int t=a; a=b; b=t; } swap_wrong swaps the local variables a,b which are unknown outside of the function void swap(int *a, int *b) { int t=*a; *a=*b; *b=t; } Function call: swap(&x, &y); Inf2C Computer Systems 2010-2011 23

Pointer arithmetic and arrays C allows arithmetic on pointers: int a[10]; int *p; p = &a[0]; // p points to a[0] p+1 points to a[1] Note that &a[1] = &a[0]+4 The compiler multiplies +1 with the data type size In general: p+i points to a[i], *(p+i) is a[i] Even *(a+i) p[i] are allowed but cannot change what a points to. It s not a variable Inf2C Computer Systems 2010-2011 24

More pointer arithmetic Common expressions: *p++ use value pointed by p, make p point to next element *++p as above, but increment p first (*p)++ increment value pointed by p, p is unchanged Special value NULL used to show that a pointer is not pointing to anything NULL is typically 0, so statements like if (!p) are common Dereferencing a NULL pointer is a very common cause of C program crashes Inf2C Computer Systems 2010-2011 25

Example pointer arithmetic Return the length of a string: int strlen(char *s) { char *p=s; while (*s++!='\0') ; return s-p; } Argument/variable s is local, so we can change it Pointer increment, dereference and comparison all in one! No statement in the loop body Note pointer subtraction at return statement Inf2C Computer Systems 2010-2011 26

Dynamic memory allocation Pointers are not much use with statically allocated data Library function malloc allocates a chunk of memory at run time and returns the address int *p; if ((p = malloc(n*sizeof(int))) == NULL) { // Error }... free(p); // release the allocated memory Inf2C Computer Systems 2010-2011 27

Pointers to pointers Consider an array of strings: char *strtable[10]; The strings are dynamically allocated any size But the table size is fixed to 10 strings How can we have both dynamically changing in size at runtime? char **strtable; Since a pointer is a variable, we could have another pointer pointing to it: pointer to pointer! Inf2C Computer Systems 2010-2011 28

Pointers to pointers - details Space must be allocated both for the table and the strings themselves char **strtable; strtable = malloc(n*sizeof(char *)); for (i=0; i < n; i++) {... // s gets a string of length l *(strtable+i) = malloc(l*sizeof(char)); strcpy(strtable[i], s); } // strtable[i][j] == *(*(strtable+i)+j) Inf2C Computer Systems 2010-2011 29

That s all folks Not all C features have been covered, but this introduction should be enough to get you started Useful things to learn on your own: Standard input/output: printf, scanf, getc, File handling: fopen, fscanf, fprintf, Inf2C Computer Systems 2010-2011 30