15213 C Primer 17 September 2002. Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.

Slides:



Advertisements
Similar presentations
C Intro.
Advertisements

Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
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:
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
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.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
CSSE 332 Functions, Pointers in C. 2 Functions - why and how ? If a problem is large If a problem is large Modularization – easier to: Modularization.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
Informationsteknologi Monday, September 10, 2007Computer Systems/Operating Systems - Class 31 Today’s class Review of more C Operating system overview.
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
Pointers and Arrays C and Data Structures Baojian Hua
CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB.
C Primer CAS CS210 Ying Ye Boston University. Outline Hello, world Basics in C Comparison of C and Java.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
Pointers CSE 2451 Rong Shi.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
Outline Midterm results Static variables Memory model
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Weeks 5-6 Pointers and Arrays Basic pointer type Pointers and Arrays Address arithmetic Pointer Arrays User-defined data types Structures Unions Pointers.
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”
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
Functions & Pointers in C Jordan Erenrich
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
Computer Systems Programming. This course gives you an overview of how computer systems are organized This course provides skills and knowledge of C and.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Object Oriented Programming Lecture 2: BallWorld.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
C/C++ Tutorial.
C Primer.
CSE 220 – C Programming Pointers.
Day 03 Introduction to C.
CSE 451 C refresher.
Command Line Arguments
An Introduction to C Programming
Day 03 Introduction to C.
C Basics.
CSCI206 - Computer Organization & Programming
Programmazione I a.a. 2017/2018.
Computer Science 210 Computer Organization
C and assembly (motivation)
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Memory Allocation CS 217.
Outline Defining and using Pointers Operations on pointers
Homework Continue with K&R Chapter 5 Skipping sections for now
15213 C Primer 17 September 2002.
C Tutorial Adapted from Wei Qian’s C tutorial slides.
Presentation transcript:

15213 C Primer 17 September 2002

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

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;

datatypesizevalues char1-128 to 127 short2-32,768 to 32,767 int4-2,147,483,648 to 2,147,483,647 long4-2,147,483,648 to 2,147,483,647 float43.4E+/-38 (7 digits) double81.7E+/-308 (15 digits long) Simple Data Types

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 int main(int argc, char* argv[]) { int i; factorial(i); return 0; }

Java programmer gotchas (3) Error handling –No exceptions –Must look at return values

“Good evening” #include int main(int argc, char* argv[]) { /* print a greeting */ printf("Good evening!\n"); return 0; } $./goodevening Good evening! $

Breaking down the code #include –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

C Preprocessor #define FIFTEEN_TWO_THIRTEEN \ "The Class That Gives CMU Its Zip\n" int main(int argc, char* argv[]) { printf(FIFTEEN_TWO_THIRTEEN); return 0; }

After the preprocessor (gcc –E) int main(int argc, char* argv) { printf("The Class That Gives CMU Its Zip\n"); return 0; }

Conditional Compilation #define CS213 int main(int argc, char* argv) { #ifdef CS213 printf("The Class That Gives CMU Its Zip\n"); #else printf("Some other class\n"); #endif return 0; }

After the preprocessor (gcc –E) int main(int argc, char* argv) { printf("The Class That Gives CMU Its Zip\n"); return 0; }

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

Command Line Arguments (3) $./cmdline The Class That Gives CMU Its Zip 8 arguments 0:./cmdline 1: The 2: Class 3: That 4: Gives 5: CMU 6: Its 7: Zip $

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

Structures Aggregate data #include 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.

c d int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘c’, d = ‘d’; Memory layout and addresses

?? f f_addr ? any float any address ?4300 f f_addr Using Pointers (1) float f; /* data variable */ float *f_addr; /* pointer variable */ f_addr = &f; /* & = address operator */

Pointers made easy (2) *f_addr = 3.2;/* indirection operator */ float g = *f_addr;/* indirection: g is now 3.2 */ f = 1.3;/* but g is still 3.2 */ f f_addr f f_addr

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

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;

Example 3: scanf #include 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()

Not like Java No new 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));

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!