Introduction to C. Acknowledgement: These slides are adapted from lecture slides made available by Prof. Dave O Halloran (Carnegie Mellon University)

Similar documents
Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Sources: On the Web: Slides will be available on:

The C Programming Language course syllabus associate level

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

How To Write Portable Programs In C

An Incomplete C++ Primer. University of Wyoming MA 5310

Informatica e Sistemi in Tempo Reale

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Lecture 22: C Programming 4 Embedded Systems

Introduction to Java

Tutorial on C Language Programming

6.s096. Introduction to C and C++

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

ECS 165B: Database System Implementa6on Lecture 2

Software Development Tools for Embedded Systems. Hesen Zhang

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Lecture Data Types and Types of a Language

Debugging and Bug Tracking. Slides provided by Prof. Andreas Zeller, Universität des Saarlands

The programming language C. sws1 1

CSC230 Getting Starting in C. Tyler Bletsch

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Crash Course in Java

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

arrays C Programming Language - Arrays

Comp151. Definitions & Declarations

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

/* File: blkcopy.c. size_t n

Java programming for C/C++ developers

Buffer Overflows. Security 2011

1 Abstract Data Types Information Hiding

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Moving from CS 61A Scheme to CS 61B Java

Semantic Analysis: Types and Type Checking

Stack Overflows. Mitchell Adair

Overview. Lecture 1: an introduction to CUDA. Hardware view. Hardware view. hardware view software view CUDA programming

Objective-C Tutorial

C++ Programming Language

Introduction to Data Structures

Computer Programming Tutorial

C++ INTERVIEW QUESTIONS

C++FA 5.1 PRACTICE MID-TERM EXAM

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

1 The Java Virtual Machine

Simple C Programs. Goals for this Lecture. Help you learn about:

Tail call elimination. Michel Schinz

Java from a C perspective. Plan

5 Arrays and Pointers

picojava TM : A Hardware Implementation of the Java Virtual Machine

Defending Computer Networks Lecture 3: More On Vulnerabili3es. Stuart Staniford Adjunct Professor of Computer Science

Java Crash Course Part I

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

System Calls and Standard I/O

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object Oriented Software Design II

Lecture 7: Machine-Level Programming I: Basics Mohamed Zahran (aka Z)

Format string exploitation on windows Using Immunity Debugger / Python. By Abysssec Inc

Networks and Protocols Course: International University Bremen Date: Dr. Jürgen Schönwälder Deadline:

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

IC4 Programmer s Manual

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

CP Lab 2: Writing programs for simple arithmetic problems

DNA Data and Program Representation. Alexandre David

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Building Embedded Systems

An Implementation of a Tool to Detect Vulnerabilities in Coding C and C++

GSM. Global System for Mobile Communications, Security in mobile phones. System used all over the world. Sikkerhed04, Aften Trusler

64-Bit NASM Notes. Invoking 64-Bit NASM

X86-64 Architecture Guide

Leak Check Version 2.1 for Linux TM

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

public static void main(string[] args) { System.out.println("hello, world"); } }

SQLITE C/C++ TUTORIAL

Habanero Extreme Scale Software Research Project

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Contents. 9-1 Copyright (c) N. Afshartous

Project 2: Bejeweled

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

How To Understand How A Process Works In Unix (Shell) (Shell Shell) (Program) (Unix) (For A Non-Program) And (Shell).Orgode) (Powerpoint) (Permanent) (Processes

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Lecture 5: Java Fundamentals III

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

CS 106 Introduction to Computer Science I

Chapter 5 Names, Bindings, Type Checking, and Scopes

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Hacking Techniques & Intrusion Detection. Ali Al-Shemery arabnix [at] gmail

C Interview Questions

A deeper look at Inline functions

CTutor. Tiago Aguiar Instituto Superior Técnico, Lisboa, Portugal November 2014

Lecture 7: Programming for the Arduino

Transcription:

Introduction to C Acknowledgement: These slides are adapted from lecture slides made available by Prof. Dave O Halloran (Carnegie Mellon University) 1

Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers and dynamic memory What we will cover A crash course in the basics of C You should read the K&R C book for lots more details 2

Like Java, like C Operators same as Java: Arithmetic i = i+1; i++; i--; i *= 2; +, -, *, /, %, Relational and Logical <, >, <=, >=, ==,!= &&,, &,,! Syntax same as in Java: if ( ) else while ( ) do while ( ); for(i=1; i <= 100; i++) switch ( ) case 1: continue; break; Simple Data Types datatype size values char 1-128 to 127 short 2-32,768 to 32,767 int 4-2,147,483,648 to 2,147,483,647 long 4-2,147,483,648 to 2,147,483,647 float 4 3.4E+/-38 (7 digits) double 8 1.7E+/-308 (15 digits long) 3

Java programmer gotchas (1) int i for(i = 0; i < 10; i++) NOT for(int i = 0; i < 10; i++) Java programmer gotchas (2) Uninitialized variables catch with Wall compiler option #include <stdio.h> int main(int argc, char* argv[]) int i; factorial(i); return 0; 4

Java programmer gotchas (3) Error handling No exceptions Must look at return values Good evening #include <stdio.h> int main(int argc, char* argv[]) /* print a greeting */ printf("good evening!\n"); return 0; $./goodevening Good evening! $ 5

Breaking down the code #include <stdio.h> Include the contents of the file stdio.h Case sensitive lower case only No semicolon at the end of line int main( ) The OS calls this function when the program starts running. printf(format_string, arg1, ) Prints out a string, specified by the format string and the arguments. format_string Composed of ordinary characters (not %) Copied unchanged into the output Conversion specifications (start with %) Fetches one or more arguments For example char %c char* %s int %d float %f For more details: man 3 printf 6

C Preprocessor #define CS367 \ Computer Systems & Programming\n" int main(int argc, char* argv[]) printf(cs367); return 0; After the preprocessor (gcc E) int main(int argc, char* argv) printf( Computer Systems & Programming\n"); return 0; 7

Conditional Compilation #define CS367 int main(int argc, char* argv) #ifdef CS367 printf("computer Systems & Programming\n"); #else printf("some other class\n"); #endif return 0; After the preprocessor (gcc E) int main(int argc, char* argv) printf( Computer Systems & Programming\n"); return 0; 8

Command Line Arguments (1) int main(int argc, char* argv[]) argc Number of arguments (including program name) argv Array of char*s (that is, an array of c strings) argv[0]: = program name argv[1]: = first argument argv[argc-1]: last argument Command Line Arguments (2) #include <stdio.h> int main(int argc, char* argv[]) int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n", i, argv[i]); return 0; 9

Command Line Arguments (3) $./cmdline Computer Systems and Programming 5 arguments 0:./cmdline 1: Computer 2: Systems 3: and 4: Programming $ Arrays char foo[80]; An array of 80 characters sizeof(foo) = 80 sizeof(char) = 80 1 = 80 bytes int bar[40]; An array of 40 integers sizeof(bar) = 40 sizeof(int) = 40 4 = 160 bytes 10

Structures Aggregate data #include <stdio.h> struct name char* name; int age; ; /* <== DO NOT FORGET the semicolon */ int main(int argc, char* argv[]) struct name bovik; bovik.name = "Harry Bovik"; bovik.age = 25; printf("%s is %d years old\n", bovik.name, bovik.age); return 0; Pointers Pointers are variables that hold an address in memory. That address contains another variable. 11

Memory layout and addresses int x = 5, y = 10; float f = 12.5, g = 9.8; char c = c, d = d ; 5 10 12.5 9. 8 c d 4300 4304 4308 4312 4317 4316 Using Pointers (1) float f; /* data variable */ float *f_addr; /* pointer variable */ f f_addr?? 4300 4304 any float? any address f_addr = &f; /* & = address operator */ f f_addr? 4300 4300 4304 12

Pointers made easy (2) *f_addr = 3.2; /* indirection operator */ f f_addr 3.2 4300 4300 4304 float g = *f_addr;/* indirection: g is now 3.2 */ f = 1.3; /* but g is still 3.2 */ f f_addr 1.3 4300 4300 4304 Function Parameters Function arguments are passed by value. What is pass by value? The called function is given a copy of the arguments. What does this imply? The called function can t alter a variable in the caller function, but its private copy. Three examples 13

Example 1: swap_1 void swap_1(int a, int b) int temp; temp = a; a = b; b = temp; Q: Let x=3, y=4, after swap_1(x,y); x =? y=? A1: x=4; y=3; A2: x=3; y=4; Example 2: swap_2 void swap_2(int *a, int *b) int temp; temp = *a; *a = *b; *b = temp; Q: Let x=3, y=4, after swap_2(&x,&y); x =? y=? A1: x=3; y=4; A2: x=4; y=3; 14

Example 3: scanf #include <stdio.h> int main() int x; scanf( %d\n, &x); printf( %d\n, x); Q: Why using pointers in scanf? A: We need to assign the value to x. Dynamic Memory Java manages memory for you, C does not C requires the programmer to explicitly allocate and deallocate memory Unknown amounts of memory can be allocated dynamically during run-time with malloc() and deallocated using free() 15

No new Not like Java No garbage collection You ask for n bytes Not a high-level request such as I d like an instance of class String malloc Allocates memory in the heap Lives between function invocations Example Allocate an integer int* iptr = (int*) malloc(sizeof(int)); Allocate a structure struct name* nameptr = (struct name*) malloc(sizeof(struct name)); 16

free Deallocates memory in heap. Pass in a pointer that was returned by malloc. Example int* iptr = (int*) malloc(sizeof(int)); free(iptr); Caveat: don t free the same memory block twice! 17