C Course Lecture 4 This lecture we'll talk about: Multi-dimensional arrays. Pointer arithmetic. Pointers to structures. Multi-file programming. What is.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Programming in C Chapter 10 Structures and Unions
Structures Often we want to be able to manipulate logical entities as a whole For example, complex numbers, dates, student records, etc Each of these must.
C Language.
An introduction to pointers in c
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
C Structures Basics of structures Typedef. Data Hierarchy Byte –8 bits (ASCII character ‘A’ = ) Field –Group of characters (character string “Fred”)
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.
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.
Elementary Data Structures: Part 2: Strings, 2D Arrays, Graphs
Pointers in C Rohit Khokher
C Programming - Lecture 5
Kernighan/Ritchie: Kelley/Pohl:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
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 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
C Slides and captured lecture (video and sound) are available at:
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
Testing a program Remove syntax and link errors: Look at compiler comments where errors occurred and check program around these lines Run time errors:
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Week 9 Part 2 Kyle Dewey. Overview Announcement More with structs and memory Assertions Exam #2 Course review.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
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 - 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.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
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.
Heap Management. What is really stored on the heap? Housekeeping Users Data Buffer Next Block Data Housekeeping 0x7000 0x7008 int main() { int *x,*y;
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Lecture Contents Arrays and Vectors: Concepts of pointers and references. Pointer declarations and initialization. Pointer Operators. Dynamic Memory Allocation.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Object-Oriented Programming in C++
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.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
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?
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
Pointers *, &, array similarities, functions, sizeof.
Arrays as pointers and other stuff COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
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.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
1 Multidimensional Arrays Chapter 13 2 The plural of mongoose starts with a "p" Initializing a multidimensional array Processing by.
Windows Programming Lecture 03. Pointers and Arrays.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
User-Written Functions
Chapter 19 Data Structures
CSE 374 Programming Concepts & Tools
C Programming - Lecture 5
Pointer Arithmetic By Anand George.
C Programming - Lecture 3
Presentation transcript:

C Course Lecture 4 This lecture we'll talk about: Multi-dimensional arrays. Pointer arithmetic. Pointers to structures. Multi-file programming. What is the halting problem?

Multi-dimensional Arrays in C Last week we dealt with 1 dimensional arrays in C. C can also deal with 2 dimensional arrays (although this is rarely done) int array[3][6]; /* Declare a 2D array */ int i,j; array[0][0]= 7; /*Set an element of it */ printf ("element 1,1 is %d\n",array[1][1]); for (i= 0; i < 3; i++) { for (j= 0; j < 6; j++) { array[i][j]= 0; /* Blank the array*/ }

We can pass 2D arrays to and from functions However, to do this, we must provide a size for them Example prototype for function: void process_array (int [3][6]); void process_array (int array[3][6]) { /* Do stuff to the array */ } int thearray[3][6]; process_array(thearray); Call the array with this (in main or other function) And write the function with

Pointer Arithmetic Recall from the previous lectures that we declare a pointer with a * use an & to get the "address of" (and convert a variable to a pointer) and use a * to get the value "pointed at" int *p; int q= 5; p= &q; *p= 6; printf ("q is now %d\n",q); printf ("p is now %d\n",*p);

Pointer Arithmetic 2 A pointer is another type of array and we can mix between them in certain arrays If we define an array we can use pointers to access it int i[7]; /* An array of 7 ints */ int *j; /* A pointer to an int*/ j= i; /* j points at the start of i*/ *j= 3; /* Same as i[0]= 3 */ j= &i[0]; /* Same as j= i */ j= j+1; /* Move j to point at i[1]*/

Pointer Arithmetic Test int i[7]; int *j; j= i; /* J points at i[0] */ j= j+1; /* Moves pointer */ *j= 3; j= i; /* Same as j= &i[0] */ *j= 10; j[1]=4; j= j+5; j[1]= 5; i= i+4; /* This is an error */ j= j+7; /* J points off end of array */ *j= 4; /* This is an error */

Multiple file programming - why do it? It means that more than one person can work on a program at once It means that when your program gets big, you don't have to scout through lots of functions It means that when you change 1 file of your huge program, you don't have to change it all (But on the other hand, it is more complicated)

Multi-file programming - how Create a "header file" (a file ending in.h) which contains all the prototypes, enums, #defines, structs, typedefs etc for your code Create a number of C source code files - they should all #include your header file. Source files NOT header files contain the functions. One (and only one) of your C source code files contains main. In VC++ you have to add source files to a workspace to get them to compile properly.

Example structure pay.h Header file - enums, structs, prototypes pay.cpp #include "pay.h" int main() Get user input Call appropriate routine fileio.cpp #include "pay.h" Read records when called Writes records Make backup copies update.cpp #include "pay.h" Type in a new file for a new lecturer Change file for existing lecturer printout.cpp #include "pay.h" Print a cheque run for all lecturers Print records of individual lecturers for inspection

Things to note If a bit of source uses a function, it must have access to its prototype This is why prototypes are in the header Similarly for enums, #defines and struct definitions. Forgetting to #include the header file can seriously cause problems The functions go in the.cpp file not the.h file. It is traditional to use "" instead of <> to indicate a header file you wrote yourself #include #include "myprog.h"

The extern statement If we want to use global variables, in multi- file programming? If we define them in the header then there will be multiple copies If we define them in one file, how will all files see them? The key is to define them in one file and declare them as "extern" in other files

Extern statement Only used with global variables in multi-file projects. Says to compiler "don't worry, this is dealt with elsewhere" file1.cpp int glob_array[100]; file2.cpp extern int glob_array[100];

Pointers to struct example typedef struct great_mathematician { char name[80]; int year_of_birth; int year_of_death; char nationality[80]; } MATHEMATICIAN;. MATHEMATICIAN *cantor; cantor= (MATHEMATICIAN *)malloc (sizeof (MATHEMATICIAN)); /* Check the allocation here */ (*cantor).year_of_birth= 1845; (*cantor).year_of_death= 1918; /* Remember to close comments with a diagonal slash */ strcpy ((*cantor).name, "Georg Cantor"); strcpy ((*cantor).nationality, "German"); free(cantor); /* Don't forget to free the memory */ Consider the peculiar syntax here

Pointers to struct (2) C allows name->bit as a shorthand for (*name).bit MATHEMATICIAN *cauchy; cauchy= (MATHEMATICIAN *) malloc (sizeof (MATHEMATICIAN)); /* The sizeof Cauchy was quite large */ cauchy->year_of_birth= 1789; cauchy->year_of_death= 1857; strcpy (cauchy->name, "Augustin Louis Cauchy"); strcpy (cauchy->nationality, "French");. free(cauchy); This shorthand is always used by C programmers

Passing it to a function int main() { MATHEMATICIAN *turing; turing= (MATHEMATICIAN *) malloc(sizeof(MATHEMATICIAN)); set_up_turing(turing); /* Do stuff with the variable */ free(turing); } void set_up_turing (MATHEMATICIAN *turing) { turing->year_of_birth=1912; turing->year_of_death=1954; /* In tragic circumstances */ strcpy (turing->name,"Alan Mathison Turing"); strcpy (turing->nationality,"British"); }

What is the Halting Problem? Isn't it annoying when a program goes into an infinite loop? Wouldn't it be great if your compiler could tell if your program was going to stop before you ran it? Why don't we write a program which will look at the source code and check if it will stop or carry on forever.

How could we tell if a program would stop? int thiscodestops (char *sourcecode) /* Given source code return 1 if code will stop and 0 if it won't */ { FILE *fptr; fptr= fopen (sourcecode, "r"); if (fptr == NULL) {.. /* Lots of VERY complex code here */. return 1; }

Then we could run our debugging script int main() { if (thiscodestops("testfile.c")) { printf ("Congrats, your code's fine\n"); } else { printf ("Your code has a bug!\n"); } return 0; }

Why can't it work? Consider this program doihalt.c int main() { while (thiscodestops("doihalt.c")) { printf ("Nope, I'm not stopping\n"); } printf ("Actually I decided to stop!\n"); return 0; }