C Slides and captured lecture (video and sound) are available at: www.cim.mcgill.ca/~jer/C/

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Programming in C Chapter 10 Structures and Unions
C Language.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming Languages and Paradigms The C Programming Language.
Assignment 1 Background Advanced OOP CS 440/540 Spring 2015 Kenneth Chiu.
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Kernighan/Ritchie: Kelley/Pohl:
Introduction to Systems Programming - Recitation Omer Kotlicki Two instances: 1.Tuesdays 15:00-16:00; Kitot Wednesdays.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
ISP - 2 nd Recitation Functions Pointers Structs Files Code Examples Homework!
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
C Slides and captured lecture (video and sound) are available at:
Week 7 – String. Outline Passing Array to Function Print the Array How Arrays are passed in a function call Introduction to Strings String Type Character.
The switch Statement.  Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Introduction to Data Structures Systems Programming Concepts.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
Gator Engineering Google Code Jam 2015 Copyright © 2008 W. W. Norton & Company. All rights reserved. 1.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
C Language Elements Preprocessor Directives # (sign for preprocessor directive commands) #include Standard header file (.h) Library.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Numbers in ‘C’ Two general categories: Integers Floats
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Pointer Data Type and Pointer Variables II
C Basics.
Basic notes on pointers in C
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
WEEK-2.
Programming Languages and Paradigms
An Overview of C.
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

C Slides and captured lecture (video and sound) are available at:

Crash Course -- Review Last week, we covered: variable declarations and assignments float x;double d = 5;int *p, i, a[100];char s[21]; y = z = 4 + 5; x += 1; ++x; y = x--; formatted I/O int snum; float gr; char mark; char name[80]; scanf ("%d %f %c %s", &snum, &gr, &mark, name); printf (”%s\’s mark is %f or %c\n”,name, mark, gr); loops while (1) printf ("hi"); for (j = 0; j * j <= up; j++) printf ("%d \n", j * j);

Exercise: Caesar's code Input: sequence of capital letters Output: another sequence of capital letters obtained by shifting each letter in the original sequence three places in the alphabet. Note: shifting wraps around. Example: KENNEDY -> NHQQHGB recall the use of this handy string function: int strlen(char *); example: n = strlen ("there"); /* n is assigned 5 */

Crash Course -- Part II Today, we will cover: functions types pointers arrays structures using linked lists simple debugging

Functions /* Increment; takes an integer argument and * returns the argument plus one. */ int incr (int i) { int j; j = i + 1; return j; } main () { int k, m = 4; k = incr(m); printf ("k = %d, m = %d\n", k, m); } output: k = 5, m = 4

More about Functions might have no return type, and no return statement: void printhi () { printf ("hi\n"); } parameters are copied and can be modified int incr (int i) { i++; return i; } default (unspecified) return type is int

Variables within Functions But this does not work: void no_incr (int i) { i++; } void main () { int x = 5; no_incr(x); printf ("%d\n", x); } beware that modifications are on internal copies of the parameters. note: void main() since main does not return a value

Exercise Write a function that checks whether a sentence has 'title case': Arguments: sentence string Assume the string consists of letters and blanks only. Return true iff each word in the sentence starts with a capital letter and continues with lowercase letters.

C Preprocessor Directives Operations before compilation phase: include "header" files that contain pre-supplied functions: #include this line will be substituted by the contents of the file define symbolic constants: #define MY_LARGE_NUMBER #define MY_NIFTY_STRING "abc"

Make your own booleans C has boolean operations on int: == != && || ! However, C has no boolean type. Make it! #define boolean_t int; #define TRUE 1 #define FALSE 0 Example: boolean_t xIsFive, zAsBig, result; xIsFive = (x == 5); zAsBig = (z >= x); if (xIsFive || zAsBig) { result = TRUE; }

Naming your own type A better way: use typedef typedef int boolean_t; Syntax: typedef existing-type new-type; Comments: typedef does not create a new type only creates a new label for an existing type makes your code easier to read

typedef in action Example: typedef char * string_t; typedef int boolean_t; string_t msg = "No more room"; boolean_t full_class; if (num_students >= MAX_SIZE) full_class= TRUE;

i == *pi Pointers C relies heavily on pointers: int i; int *pi; pi = &i; *pi = 3; 3 pi

Pointers and Arrays An array name by itself is a pointer to the first element: int a[100]; *a = 5; /* same as a[0] = 5 */ *(a + 3) = 10; /* same as a[3] = 10; */ /* Note: *a + 3 means something else */ Strings are arrays of char: char s[3]; strcpy (s, "hi"); /* same as following line */ s[0] = 'h'; s[1] = 'i'; s[2] = '\0';

4 j i Call by reference void incr (int *i); /* * increment i by 1 */ { *i = *i + 1; } main() { int j; j = 4; incr (&j); printf ("j = %d\n", j); } &j and i are pointers to the same integer: incr can change the integer (side effect), but not the pointer

Dynamic Memory Allocation Pointer errors can be nasty void main () { int *p; *p = 5; } Reserve space for the "pointed to" object: #include void main () { int *p; p = (int *)malloc (sizeof (int)); *p = 5; printf ("value at p = %d\n", *p); free (p);/* must do this yourself! */ }

Finding Bugs Insert "print" statements: printf ("At point A, %s = %d\n", "x", x); Use a debugger to help you catch bugs in the act: run step-by-step insert breakpoints display variables

Programming Errors I #include void main () { int i; scanf ("%d", &i); if (i = 0) puts ("false"); else puts ("true"); } What’s wrong?

Programming Errors I #include void main () { int i; scanf ("%d", &i); if (i = 0) puts ("false"); else puts ("true"); } The assignment, i = 0, will return a value of 0, so the program will always output "true" Use: if(0 == i) to be safe

Programming Errors II #include void main () { int i; /* echo one number */ scanf ("%d", i); printf ("input = %d\n", i); } What’s wrong? Hint: Segmentation fault / Bus error

Programming Errors II #include void main () { int i; /* echo one number */ scanf ("%d", i); printf ("input = %d\n", i); } Must provide the address of an integer if the function is going to assign a value to it.

Programming Errors III #include void main () { int *pc; scanf ("%d", pc); printf ("%d\n", pc); } What’s wrong?

Programming Errors III #include void main () { int *pc; scanf ("%d", pc); printf ("%d\n", pc); } *pc is an uninitialized pointer so results are unpredictable --> use malloc

Programming Errors IV #include void main () { double *p; p = malloc (sizeof (double *)); } What’s wrong?

Programming Errors IV #include void main () { double *p; p = malloc (sizeof (double *)); } Insufficient memory allocated for a double (typically, 8 bytes) Use malloc (sizeof (double));

Programming Errors V #include void main () { char s[] = "hi"; if (s == "hi") puts ("Strings are equal"); else puts ("Strings are not equal"); } What happens?

Programming Errors V #include main () { char s[] = "hi"; if (s == "hi") puts ("Strings are equal"); else puts ("Strings are not equal"); } Use strcmp() to compare strings, otherwise you are comparing addresses.

Structures Use struct to create or define a new type: struct str_data { char *string; int length; }; struct str_data s1, s2; Syntax struct structure_name { type1 member1; type2 member2; … }; A member of a structure is referred to by: structure_name.member

Structures, cont. Example: struct str_data { char *string; int length; }; struct str_data s1, s2; s1.string = (char *) malloc(80); strcpy (s1.string, "How now brown cow."); s1.length = strlen(s1.string); s2 = s1; /* can copy structures, pass to fcns */

Arrays of Structures Example: #define MAX_STUDENT 100 typedef struct { /* define a new type */ char name[80]; int name_len; int student_number; } student_t; /* create list of elements of type student_t */ student_t class[MAX_STUDENT]; for (i = 0; i < MAX_STUDENT; i++) { gets(class[i].name); class[i].name_len = strlen(class[i].name); }