C Programming - Lecture 5

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

C Programming lecture 2 Beautiful programs Greek algorithms
C Programming Course Overview
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
SEE C GO Provisional Title. Syntax Types int, float, double, char, void Identifiers foo Operators + - * / ^ Delimiters ; {} () “” ‘’ Keywords return,
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
C++ Basics Variables, Identifiers, Assignments, Input/Output.
C Programming Revision Malcolm Wilson. Variables Types int, char, double, long. NO type for string see later. unsigned above. assignment X=2 ; C=‘v’;
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
DCO1 Performance Measurement and Improvement Lecture 7.
C Programming - Lecture 7 This lecture we will learn: –How to write documentation. Internal docs. External docs. User docs. (But not much about this).
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
Structure of a C program
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
Guide To UNIX Using Linux Third Edition
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
C Course Lecture 4 This lecture we'll talk about: Multi-dimensional arrays. Pointer arithmetic. Pointers to structures. Multi-file programming. What is.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Review C Language Features –control flow –C operators –program structure –data types –I/O and files Problem Solving Abilities.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
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.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Agenda Attack Lab C Exercises C Conventions C Debugging
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
Computational Biology, Part B C, C++, Java Review Zia Khan Robert F. Murphy Copyright  All rights reserved.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a wrappered function? –How to assess efficiency. –What is a clean interface?
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
By Anand George SourceLens.org Copyright. All rights reserved. Content Owner - Meera R (meera at sourcelens.org)
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Object Oriented Programming Lecture 2: BallWorld.
C++ Lesson 1.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
A bit of C programming Lecture 3 Uli Raich.
C Programming Course Overview
LESSON 3 IO, Variables and Operators
C Short Overview Lembit Jürimägi.
Introduction to C Programming Language
Reserved Words.
פרטים נוספים בסילבוס של הקורס
פרטים נוספים בסילבוס של הקורס
Pointers.
Govt. Polytechnic,Dhangar
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
Variables in C Declaring , Naming, and Using Variables.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Programming Language C Language.
C Programming - Lecture 5
Building Blocks of C Programming Language
C Language B. DHIVYA 17PCA140 II MCA.
C Programming - Lecture 3
Pointers.
Presentation transcript:

C Programming - Lecture 5 This lecture we will learn: Why I harp on about pointers. Arrays of pointers. What are command line arguments. The realloc command. The difference between an array and a pointer. Why pointers are dangerous as well as confusing. All the rest of the C language.

What's the point of pointers? Pointers can be used as variable length arrays. Pointers can be used for advanced data structures. Pointers can be "cheaper" to pass around a program. You could program without using them but you would be making life more difficult for yourself. Some things simply can't be done sensibly in C without them.

Arrays of pointers More commonly used (by experienced programmers) is an array of pointers. We can use an array of pointers in a similar way to a multi-dimensional array. We can declare an array of pointers like so: char *name[]= {"Dave","Bert","Alf"}; /* Creates and initialises 3 names */ We can now use name[0] anywhere we could use a string.

Example of pointer arrays int i; char *people[]= {"Alf","Bert","Charlie"}; for (i= 0; i < 3; i++} { printf ("String %d is %s\n",i+1,people[i]); } Will print: String 1 is Alf String 2 is Bert String 3 is Charlie

Example of pointer arrays (2) int *lists[100]; /* Get 100 ptrs to int */ int i; for (i= 0; i< 100; i++) { lists[i]= (int *)malloc(23*sizeof(int)); } /* Do something with them here */  for (i= 0; i < 100; i++) { free(lists[i]);

What are Command line arguments? In unix we can type, for example, In windows we can do similar things though it is more tricky (and less commonly used). The myfile1.dat and myfile2.dat are known as command line arguments But how would we write a C program which could listen to command line arguments mv myfile1.dat myfile2.dat

Arguments to main introduce command line arguments Instead of writing Write argc tells us the number of command line arguments argv[0] is the first, argv[1] is the second, argv[2] is the third etc. int main() int main(int argc, char *argv[])

Example code to print arguments int main (int argc, char *argv[]) { int i; for (i= 0; i < argc; i++) { printf ("Argument %d is %s",i+1, argv[i]); } return 0;

Using command line arguments int main(int argc, char *argv[]) { FILE *fptr; if (argc < 2) { /* Do some error handling */ } fptr= fopen (argv[1],"r"); if (fptr == NULL) { /* Do some other error handling */ return 0;

Realloc Realloc it is for times when you've used malloc to get the size of array but need it bigger again (or perhaps smaller). Realloc allows you to say "the memory I grabbed before was the wrong size - I need to change the size but keep the first bit the same). You will probably not use realloc much. In any case realloc is inefficient.

What's the difference between an array and a pointer Arrays have memory already allocated. We cannot move an array to point at something else. There's no such thing as a multi-dimensional pointer (but you can fake one). We cannot use arrays for our complicated data types (see later lectures).

The true HORROR of pointers Pointer programming allows more sophisticated programming technique. But if we mess up with pointers, we really mess up. It is best to only use pointers once you are confident with simpler programming techniques. Pointer bugs are the hardest to find - you might find your program crashes randomly at different points in the code. This is typical of pointer bugs.

Writing to unassigned memory int *a; *a= 3; /* Writes to a random bit of memory */ a= malloc (100*sizeof(int)); /* malloc memory for 100 ints */ a[100]= 3; /* Writes to memory off the end of the array */ /* malloc memory for 100 ints*/ . . /* Do some stuff with a*/ free (a); /* free it again */ . /* Do some other stuff during which we forget a is freed */ *a= 3; /* Writes to memory which has been freed – very bad*/

Memory leaks If we allocate memory but don't free it this is a "memory leak" void my_function (void) { int *a; a= malloc(100*sizeof(int)); /* Do something with a*/ /* Oops – forgot to free a */ } Every time we call this function it "steals" 100 ints worth of memory. As we call this function more the computers memory will fill up.

Rogue pointers Rogue pointers are pointers to unassigned memory. If we try to access rogue pointers we will be writing to unassigned memory int *calc_array (void) { int *a; int b[100]; /* Calculate stuff to go in b */ a= b; /* Make a point to the start of b*/ return a; /* Ooops – this isn't good */ }

Pointers to pointers? We can also have pointers to pointers: We can even have pointers to functions: If you want to use them then feel free. int number= 5; int *ptrnumber; int **ptrtoptrtonumber; *ptrtonumber= &number; *ptrtoptrtonumber= &ptrtonumber; *(*ptrtoptrtonumber)= 6; ptrtonumber number ptrtoptrtonumber 5

Keywords of C revisited Flow control (6) – if, else, return, switch, case, default Loops (5) – for, do, while, break, continue Common types (5) – int, float, double, char, void structures (3) – struct, typedef, union Counting and sizing things (2) – enum, sizeof Rare but still useful types (7) – extern, signed, unsigned, long, short, static, const Evil keywords which we avoid (1) – goto Wierdies (3) – auto, register, volatile

Now we KNOW all of C You now know _all_ of the C language (with the exception of some teeny bits mentioned in your notes). I haven't taught you all the library functions - most of these are in the photocopies you were given. Subsequent lectures will teach something about programming style, how to document code and how to program efficiently.