1 C Basics. 2 The C Language Spirit Made by professional programmers for professional programmers Very flexible, very efficient, very liberal Does not.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Programming Languages and Paradigms The C Programming Language.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Kernighan/Ritchie: Kelley/Pohl:
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
1 CSSE 332 Preprocessor, Array and Strings. 2 External library files libname.a or libname.so Special functionality is provided in the form of external.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
CSSE221: Software Dev. Honors Day 28 Announcements Announcements Simulation grades coming back Simulation grades coming back All C Projects due Friday.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction.
Guide To UNIX Using Linux Third Edition
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
Pointers Applications
An Introduction to C Programming Geb Thomas. Learning Objectives Learn how to write and compile a C program Learn what C libraries are Understand the.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C Preprocessor.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 19 - The Preprocessor Outline 19.1 Introduction 19.2 The #include Preprocessor Directive 19.3.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Tutorial Session #2 Type conversions More on looping Common errors Control statements Pointers and Arrays C Pre-processor Makefile Debugging.
CS 450 MPX P ROJECT A Quick C Review. P OINTERS AND ADDRESSES IN C Check Manual I2 from Dr. Mooney’s website for a complete review of C topics you will.
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.
C Hints and Tips The preprocessor and other fun toys.
CSCI 171 Presentation 8 Built-in Functions, Preprocessor Directives, and Macros.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessing Lecture 12 April 7, 2005.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
Copyright ©: University of Illinois CS 241 Staff1 C Survival Guide.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
Correct C Programs. The C compiler cc [filename.c] Options include: -o [output file name] -lm to include the maths library -E to get output from preprocessor.
Strings, Pointers and Tools
THE PREPROCESSOR
The Preprocessor Directives Introduction Preprocessing – Occurs before program compiled Inclusion of external files Definition of symbolic constants.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
1 C Basics. 2 The C Language Spirit Made by professional programmers for professional programmers Very flexible, very efficient, very liberal Does not.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Hank Childs, University of Oregon April 13 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
13 C Preprocessor.
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Chapter 13 - The Preprocessor
C programming language
C Basics.
Arrays in C.
User-Defined Functions
Computer Science 210 Computer Organization
Pointers and Pointer-Based Strings
Presentation transcript:

1 C Basics

2 The C Language Spirit Made by professional programmers for professional programmers Very flexible, very efficient, very liberal Does not protect the programmers from themselves. Rationale: programmers know what they are doing even UNIX and most “serious” system software (servers, compilers, etc) are written in C. Can do everything Java and C++ can. It’ll just look uglier in C

3 Compiler gcc See manual “man” for options man gcc Preprocessor Compiler Linker C89 versus C99 C99: Mix variable declarations and code make – a compilation utility Google for make files (or GNU Make)

4 Programming in C C = Variables + Instructions

5 Programming in C C = Variables + Instructions int char float string … pointer array

6 Programming in C C = Variables + Instructions int char float string … pointer array printf/scanf assignment if switch … for while

7 10,000 10,002 10,008 10,010 10,012 … Variables Value1 Value2 Value3 Value4 Value5 x y z p d Memory Address Name Value

8 10,000 10,002 10,008 10,010 10,012 … The “&” Operator: Reads “Address of” Value1 Value2 Value3 Value4 Value5 x y z p d Name Value &y

9 10,000 10,002 10,008 10,010 10,012 … Pointers Value1 Value2 Value3 10,002 Value5 x y z p d Name Value A pointer is a variable whose value is the address of another

10 10,000 10,002 10,008 10,010 10,012 … The “*” Operator Reads “Variable pointed to by” Value1 Value2 Value3 10,002 Value5 x y z p d Name Value A pointer is a variable whose value is the address of another *P

11 What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); }

12 What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } @*%^ p q x

13 What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } 10 p q x

14 What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } 10 p q x

15 What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } 11 p q x

16 What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } 11 p q x

17 Cardinal Rule: Must Initialize Pointers before Using them int *p; *p = 10; BAD

18 Cardinal Rule: Must Initialize Pointers before Using them int *p; *p = 10; p ?? Pointing somewhere random

19 Cardinal Rule: Must Initialize Pointers before Using them int *p; *p = 10; p 10

20 How to Initialize Pointers

21 How to Initialize Pointers Set pointer equal to location of known variable int *p; int x; … p=&x;

22 How to Initialize Pointers Use malloc() int *p; … p=(int*) malloc (sizeof (int));

23 How to Initialize Pointers Create an Array int p[10]; Same as: int *p; p=(int*) malloc (10*sizeof (int));

24 Arrays int p[5]; p[0] p[1] p[2] p[3] p[4] Name of array (is a pointer) p Shorthand: *(p+1) is called p[1] *(p+2) is called p[2] etc..

25 Example int y[4]; y[1]=6; y[2]=2; 6 2 y[0] y[1] y[2] y[3] y

26 Array Name as Pointer What’s the difference between the examples below: Example 1: int z[8]; int *q; q=z; Example 2: int z[8]; int *q; q=&z[0];

27 Array Name as Pointer What’s the difference between the examples below: Example 1: int z[8]; int *q; q=z; Example 2: int z[8]; int *q; q=&z[0]; NOTHING!! x (the array name) is a pointer to the beginning of the array, which is &x[0]

28 Example: How much is y at the end: int y, x, *p; x = 20; *p = 10; y = x + *p;

29 Example: How much is y at the end: int y, x, *p; x = 20; *p = 10; y = x + *p; BAD!! Dereferencing an unitialized pointer will likely segfault or overwrite something! Segfault = unauthorized memory access

30 Question: What’s the difference between int* q; int q[5]; What’s wrong with: int ptr[2]; ptr[1] = 1; ptr[2] = 2;

31 Question: What is the value of b[2] at the end? int b[3]; int* q; b[0]=48; b[1]=113; b[2]=1; q=b; *(q+1)=2; b[2]=*b b[2]=b[2]+b[1];

32 Strings (Null-terminated Arrays of Char) Example char s[5]; Strings are arrays that contain the string characters followed by a “Null” character to indicate end of string. Do not forget to leave room for the null character s[0] s[1] s[2] s[3] s[4] s

33 Conventions Strings “string” “c” Character ‘c’

34 String Operations strcpy strlen srtcat strcmp

35 strcpy, strlen Syntax: strcpy(ptr1, ptr2); where ptr1 and ptr2 are pointers to char value = strlen(ptr); where value is an integer and ptr is a pointer to char Example: int len; char str[15]; strcpy (str, "Hello, world!"); len = strlen(str);

36 strcpy, strlen What’s wrong with char str[5]; strcpy (str, "Hello");

37 strncpy Syntax: strncpy(ptr1, ptr2, num); where ptr1 and ptr2 are pointers to char num is the number of characters to be copied Example: int len; char str1[15], str2[15]; strcpy (str1, "Hello, world!"); strncpy (str2, str1, 5);

38 strncpy Syntax: strncpy(ptr1, ptr2, num); where ptr1 and ptr2 are pointers to char num is the number of characters to be copied Example: int len; char str1[15], str2[15]; strcpy (str1, "Hello, world!"); strncpy (str2, str1, 5); Caution: strncpy blindly copies the characters. It does not voluntarily append the string-terminating null character.

39 strcat Syntax: strcat(ptr1, ptr2); where ptr1 and ptr2 are pointers to char Concatenates the two null terminates strings yielding one string (pointed to by ptr1). char S[25] = "world!"; char D[25] = "Hello, "; strcat(D, S);

40 strcat Example What’s wrong with: char S[25] = "world!"; strcat(“Hello, ”, S);

41 strcmp Syntax: diff = strcmp(ptr1, ptr2); where diff is an integer and ptr1 and ptr2 are pointers to char Returns zero if strings are identical int diff; char s1[25] = "pat"; char s2[25] = "pet"; diff = strcmp(s1, s2);

42 Math: Increment and Decrement Operators Example 1: int x, y, z, w; y=10; w=2; x=++y; z=--w; Example 2: int x, y; y=10; w=2; x=y++; z=w--;

43 Math: Increment and Decrement Operators Example 1: int x, y, z, w; y=10; w=2; x=++y; z=--w; Example 2: int x, y; y=10; w=2; x=y++; z=w--; First increment/decrement then assign result x is11, z is 1 First assign then increment/decrement x is 10, z is 2

44 Math: Increment and Decrement Operators on Pointers Example 1: int a[2]; int number1, number2, *p; a[0]=1; a[1]=10; a[2]=100; p=a; number1 = *p++; number2 = *p; What will number1 and number2 be at the end?

45 Math: Increment and Decrement Operators on Pointers Example 1: int a[2]; int number1, number2, *p; a[0]=1; a[1]=10; a[2]=100; p=a; number1 = *p++; number2 = *p; What will number1 and number2 be at the end? Hint: ++ increments pointer p not variable *p

46 Logic: Relational (Condition) Operators == equal to != not equal to > greater than < less than >= greater than or equal to <= less than or equal to

47 Logic Example if (a == b) printf (“Equal.”); else printf (“Not Equal.”); Question: what will happen if I replaced the above with: if (a = b) printf (“Equal.”); else printf (“Not Equal.”);

48 Correct C Programs

The C compiler cc [filename.c] Options include: -o [output file name] -lm to include the maths library -E to get output from preprocessor only (no compilation). For a large program you can compile a small piece at a time, and link it to larger, pre-compiled parts. To compile only, use: cc -c [filename.c] This creates object files (whose names end in.o), which can then be linked later by using them instead of the source files. The compiler works in three stages: 1. it preprocesses (replacing the #include, #define etc); 2. it compiles the preprocessed files; 3. it links all of the pieces of code together into the executable program.

C Compiler: Libraries To make the functions available to other programs, add the library to the list of compiled files: cc -o pgm main.c file1.c g_lib.a Follow this by ranlib g_lib.a which organizes the file in a form that is useful for the linker. It is possible to create libraries, which are (generally large) collections of useful object code ready for linking, so they don’t need to be compiled over and over again for different programs. To do this with a set of.o files, ar ruv g_lib.a gfopen.o gfclose.o gcalloc.o This makes a library file called g_lib.a. ar = archive ruv = replace, update, verbose g_lib.a = output archive file name object files to go in the library

Conditional compilation There is also an #ifndef, which includes lines if a name is not defined. There is also an #undef function to remove previous definitions, in order to prevent clashes. To match the #if, there is an #else; there is also #elif, which is short for else if. The preprocessor can be used to exclude code from compilation: #define DEBUG 1 /*set debug to true at top of file*/ #if DEBUG printf(“debug: a = %d\n”, a); #endif Because DEBUG has value 1, the printf statements will be compiled. The statements can be turned off by setting DEBUG = 0 at the start. An alternative is #ifdef DEBUG.... #endif which will include the lines if DEBUG is defined at all at the top.

Preprocessor macros with arguments #define SQ(x)((x) * (x)) will replace, e.g., SQ(a + b) by ((a + b) * (a + b)). Note here that all of the parentheses are needed! #define min(x, y) (((x) < (y)) ? (x) : (y)) will replace an expression such as m = min(u, v) by m = (((u) < (v)) ? (u) : (v)) The arguments of m can be arbitrary expressions of comparable type.

Writing large programs A large program will normally be stored as a collection of.h and.c files in its own directory. If we are developing a program called pgm, we make a header file pgm.h, which contains #includes, #defines and a list of function prototypes. All.c files should then have #include “pgm.h” at the top. Note the use of quotes rather than in, when you include your own header files. The compiler then looks in the current directory rather than in the directory for standard C header files.

Header files in large programs Often the same header files are included in several different source code files. How to avoid multiple definitions when the header file is compiled repeatedly? Let us assume we have a header file called MyHeaderFile1.h.: #ifndef MYHEADERFILE1 #define MYHEADERFILE1.... function prototypes;.... definitions; #endif Thus, the material in the file is only included if it hasn’t been included already. this is only compiled if MYHEADERFILE1 is not defined (i.e. if the header file has not been processed before)

Program Correctness You thought that you implement the program correct, but it crashes. Why? A common problem: memory Do you allocate any buffer? Do you allocate enough space? Do you free it only once?

Segmentation Violations and Bus Errors #include main() { char *s; s = NULL; printf("%d\n", s[0]); } (1)What will it happen? (2) Why?

Importance of Writing Correct Programs char buf[80]; printf(“Enter your first name”); scanf(“%s”, buf); Any problem? Problem: if the user enters more than 79 bytes, the resulting string and the string terminator \0 do not fit in the allocated variable!! Possible Fix of the Problem? char buf[80]; printf(“Enter your first name”); scanf(“%79s”, buf);. Buffer Overflow

Library Function Calls Traditional UNIX – returns 0 successful, - 1 unsuccessful, sets errno POSIX Standard Committee decides that no ‘errno’ be used. Instead: all new functions return error code Good coders handle ALL errors, not just mandatory (in the standard) ones.

Error reporting perror function outputs to standard error a message corresponding to the current value of errno No return values of errors are defined by perror #include void perror(const char * s); strerror function returns a pointer to the system error message corresponding to the error code errnum If successful, strerror returns a pointer to the error string #include char *strerror(int errnum);

Handling Errors Always handle all errors Either: Print error message and exit program (only in main) Return -1 or NULL and set an error indicator such as errno Return an error code All functions should report errors to calling program Use conditional compilation to enclose debugging print statements cc -DDEBUG

Debug Your program Discussion: It crashes, what can I do? Tip1: Code review by yourself and others Do you know the problem is? char w[16]; char document[4096]; char docFname[128]; File *fp; int main (int argc, char **argv ){ //parsing parameters … //reading document … for(i=0; i<=docLength; i++){ if(!strcmp(&(document[i]), w)){ printf(“found!\n”); return; }

Tip2: Print Out More Debugging Info … int main (int argc, char **argv ){ //parsing parameters … //reading document … printf(“w=%s, docLength=%d”, w, docLength); for(i=0; i<=docLength; i++){ printf(“i=%d, document[i]=%c\n”, I, document[i]); if(!strcmp(&(document[i]), w)){ printf(“found!\n”); return; }

Tip3: Try Different Inputs Test case 1: the document contains the word Test case 1a: the document contains the word in the very beginning Test case 1b: the document contains the word in the very end Test case 2: the document does not contain the word Further reduce the document size to see if it changes

Tip4: Interactive Debuggers Professional engineers use interactive debuggers (gdb, Microsoft visual studio, etc) gdb You can stop the program in the middle, examine the state (variable values, etc) You can step one statement by one statement You can change the variable values