Intro to C CS 3410 (Adapted from slides by Kevin Walsh

Slides:



Advertisements
Similar presentations
IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Programming Languages and Paradigms The C Programming Language.
C Intro.
Kernighan/Ritchie: Kelley/Pohl:
Introduction to C. Why use C instead of Java Intermediate-level language: –Low-level features like raw memory tweaking –High-level features like complex.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Primitive Variable types Basic types –char (single character or ASCII integer value) –int (integer) –short (not longer than int) –long (longer than int)
Intro to C (or What You Need to Know for HW1) CS 316 Jed Liu Dept. of Computer Science Cornell University (Adapted from slides by Kevin Walsh.
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.
UBC104 Embedded Systems Variables, Structures & Pointers.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
C for Java Programmers CS 316 Kevin Walsh Dept. of Computer Science, Cornell University (Adapted from cs414 slides by Niranjan Nagarajan (Adapted.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Computer Science 210 Computer Organization Introduction to C.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Stack and Heap Memory Stack resident variables include:
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
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”
Object Oriented Programming Lecture 2: BallWorld.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
Variables Bryce Boe 2012/09/05 CS32, Summer 2012 B.
CSC 533: Programming Languages Spring 2016
Dynamic Storage Allocation
Pointers and Dynamic Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
CSC 533: Programming Languages Spring 2015
Computer Science 210 Computer Organization
C is readable... :-) What does this function do?
C Primer.
A bit of C programming Lecture 3 Uli Raich.
Functions, Part 2 of 2 Topics Functions That Return a Value
C Programming Tutorial – Part I
Programming Languages and Paradigms
C Short Overview Lembit Jürimägi.
C programming language
Programming Paradigms
C Basics.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Computer Science 210 Computer Organization
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Pointers, Dynamic Data, and Reference Types
Dynamic Memory Allocation
Memory Allocation CS 217.
Pointers.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Variables Title slide variables.
Outline Defining and using Pointers Operations on pointers
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
C Programming Getting started Variables Basic C operators Conditionals
Exercise Arrays.
Programming Languages and Paradigms
Dynamic Memory – A Review
15213 C Primer 17 September 2002.
Pointers, Dynamic Data, and Reference Types
CSC 533: Programming Languages Spring 2019
Classes and Objects Object Creation
C Tutorial Adapted from Wei Qian’s C tutorial slides.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Intro to C CS 3410 (Adapted from slides by Kevin Walsh (Adapted from cs414 slides by Niranjan Nagarajan (Adapted from slides by Alin Dobra (Adapted from slides by Indranil Gupta))))

Why use C instead of Java Intermediate-level language: Low-level features like raw memory tweaking High-level features like complex data-structures Access to all the details of the implementation Explicit memory management Explicit error detection More power than Java (so may be made faster) All this make C a far better choice for system programming.

Common Syntax with Java Basic types are similar (int, short, double…) Operators: Arithmetic: + - * / % ++ -- *= += ... Relational: <,>,<=,>=,==,!= Logical: &&, ||, !, ? : Bit: &,|,^,!,<<,>>

Common Syntax with Java (cont.) Language constructs: if( ) {...} else {...} while( ) {...} do {...} while( ); for (i=0; i<100; i++) {...} switch( ) { case 0: ... break; ... } break, continue, return No exception handling statements  most functions return errors as special values (e.g., a negative number). Check for these!

Hello World Example hello.c /* Hello World program */ #include <stdio.h> #include <stdlib.h> int main(int ac, char **av) { printf("Hello World."); } $ ./hello Hello World. bash or cmd.exe

Primitive Types Integer types: char : used to represent ASCII characters or one byte of data (not 16 bit like in Java) int, short and long : versions of integer (architecture dependent, usually 4, 2, and 4 bytes) signed char/short/int/long unsigned char/short/int/long  conversion between signed/unsigned often does unexpected things Floating point types: float and double like in Java. No boolean type, int usually used instead. 0 == false everything else == true

Primitive Types Examples char c='A'; char c=65; int i=-2343234; unsigned int ui=100000000; float pi=3.14; double long_pi=0.31415e+1;

Arrays and Strings Arrays: int A[10]; // declare and allocate space for array for (int i=0; i<10; i++) // initialize the elements A[i]=0; Strings: arrays of char terminated by ‘\0’ char char name[] ="CS316"; //{'C','S',‘3','1',‘6','\0'} name[2] = '3'; name[4]++; Strings are mutable Common functions strcpy, strcmp, strcat, strstr, strchr, strdup. Use #include <string.h>

Pointers An 'address' is an index to a memory location (where some variable is stored). A 'pointer' is a variable containing an address to data of a certain type. Declaring pointer variables: int i; int* p; // p points to some random location – null pointer Creating and using pointer values p = &i; // p points to integer i – p stores the address of i (*p) = 3; // variable pointed by p takes value 3 & is the address-of operator, * is the dereference operator. Similar to references in Java. Pointers are nearly identical to arrays in C array variables can not be changed (only the contents can change)

Memory variable names i name c A p ps int i = 6; ... addresses 0000 0004 0008 … 1054 … 1820 1824 1828 6344 6348 variable names i name c A p ps int i = 6; ... char name[] = "cs316"; char c = name[1]; short A[6]; for (i = 0; i < 6; i++) A[i] = i*i; int *p; p = &i; short *ps; ps = &A[1]; 6 'c' 's' '3' '1' '6' \0 's' 1 4 9 16 25 1054 6346

Pointers (cont.) Attention: dereferencing an uninitialized pointer can have arbitrary effects (bad!) (including program crash). Dereferencing a NULL pointer will crash the program (better!) Advice: initialize with NULL, or some other value if not sure of value, check it before dereferencing if (p == NULL) { printf("ack! where's my pointer!\n"); exit(1); }

Structures Like Java classes, but only member variables no static variables no functions struct birthday { char* name; char month; short day; int year; }; struct birthday mybirthday = {"elliot",8,21,2002}; mybirthday.name[0] = 'E'; if (mybirthday.month == 6) printf("%s is a Cancer\n", mybirthday.name); mybirthday 0xdeadbeef 8 21 2002

Structures (cont.) Members of a struct can be of any type that is already defined. Trick: 'struct X' can contain a pointer to 'struct X' struct intlist { int data; struct intlist* next; }; -> is syntax sugaring for dereference and take element: struct intlist one = {10, NULL}; struct intlist two = {20, NULL}; struct intlist *head = &one; one->next = &two; (*one).next = &two; // Does same thing as previous line

printf function printf(formating_string, param1, ...) Formating string: text to be displayed containing special markers where values of parameters will be filled: %d for int %c for char %f for float %g for double %s for null-terminated strings Example: int numstudents = 39; printf("The number of students in %s is %d.", name, numstudents);  printf will not complain about wrong types, number of params, etc.

enum: enumerated data-types enum months { JANUARY, FEBRUARY, MARCH, ... }; Each element of enum gets an integer value and can be used as an integer. enum signs { CANCER = 6, ARIES = 1,

Memory Allocation and Deallocation Global variables: declared outside any function. Space allocated statically before program execution. Initialization statements (if any) done before main() starts. Space is deallocated when program finishes. Name has to be unique for the whole program.

Memory Allocation and Deallocation Local variables: declared in the body of a function or inside a '{ }' block. Space allocated when entering the function/block. Initialization (if any) before function/block starts. Space automatically deallocated when function returns or when block finishes  Attention: referring to a local variable (by means of a pointer for example) after the function returned will cause unexpected behavior. Names are visible only within the function/block

Memory Allocation and Deallocation Heap variables: memory has to be explicitly allocated: void* malloc(int) (similar to new in Java) char *message = (char *)malloc(100); intlist *mylist = (intlist *)malloc(sizeof(intlist)); mylist->data = 1; mylist->next = (intlist *)malloc(sizeof(intlist)); mylist->next->data = 2; mylist->next->next = NULL; deallocated: void free(void*) free(msg); msg = NULL; free(mylist->next); free(mylist); mylist = NULL;

Malloc/Free and pointers You must malloc() reading/writing from random addresses is bad. You must malloc() the right amount: reading/writing over the end of the space is bad sizeof(struct birthday) strlen(name)+1; // +1 is for the '\0' You must free() No garbage collector; if you don't have a free() for every malloc(), you will eventually run out of memory. … but not too much Freeing same memory twice is bad ("double free"). …and don't use the memory after it is freed set pointers to NULL after free.

Memory Allocation and Deallocation struct birthday *clone_student(struct birthday *b) { struct birthday *b2 = (struct birthday *)malloc(sizeof(struct birthday)); b2->name = (char *)malloc(strlen(b->name)+1); // or use strdup() memcpy(b2->name, b->name, strlen(b->name)+1); b2->day = b->day; b2->year = b->year; b2->month = b->month; return b2; } void rename(struct birthday *b, char *new_name) { free(b->name); // danger: b->name must be a heap variable b->name = strdup(new_name); // same as malloc(...) then memcpy(...)

Functions Can declare using a prototype, then define the body of the function later lets function be used before it is defined. Arguments passed by value Use pointers to pass by reference Return value passed by value Use malloc()'ed pointer to return by reference

Functions ­ Basic Example #include <stdio.h> int sum(int a, int b); // function declaration or prototype int main(int ac, char **av){ int total = sum(2+2,5); // call function sum with parameters 4 and 5 printf("The total is %d\n", total); } /* definition of sum; has to match prototype */ int sum(int a, int b) {// arguments passed by value return (a+b); // return by value

Why pass via pointers? void swap(int, int); int main(int ac, char **av) { int five = 5, ten = 10; swap(five, ten); printf("five = %d and ten = %d", five, ten); } void swap(int n1, int n2) /* pass by value */ int temp = n1; n1 = n2; n2 = temp; $ ./swaptest five = 5 and ten = 10 NOTHING HAPPENED

Why pass by reference?(cont.) void swap(int *, int *); int main(int ac, char **av) { int five = 5, ten = 10; swap(&five, &ten); printf("five = %d and ten = %d", five, ten); } void swap(int *p1, int *p2) /* pass by value */ int temp = *p1; *p1 = *p2; *p2 = temp; $ ./swaptest five = 10 and ten = 5