Programming in C Lecture Tiina Niklander

Size: px
Start display at page:

Download "Programming in C Lecture Tiina Niklander"

Transcription

1 Programming in C Lecture Tiina Niklander Liisa Marttinen & Tiina Niklander C programming

2 Week 4 covers Multidimensional arrays Pointer arrays Command-line arguments Please note that there are less numbered exercises, but each subtask will give you TMC points, so please submit also partially solved exercises Liisa Marttinen & Tiina Niklander C programming

3 More about types: Remember that C does not have fixed type sizes, except char is stored in one byte The type sizes are promised to be short int <= int <= long int (<=long long int) unsigned versions of these float <= double <= long double Special fixed-size types: stdint.h int8_t, int16_t, int32_t, int64_t uint8_t, uint16_t, uint32_t, uint64_t (for portability; standardised in C99) Liisa Marttinen & Tiina Niklander C programming

4 Stack and heap, scope of variable Faculty of Science Department of Computer Science

5 Process structure Stallings: Operating systems Process control block (PCB): Program code Heap for data Stack (grows from larger memory addresses towards smaller) Memory addresses of process s own memory area

6 Stack (pino) (function call stack) Implicit usage (function arguments and local variables) push top pop Advantage: No explicit memory allocation or release. Disadvantage: Elements in the stack can be used only when in the stack (= during function execution) Error case: dangling reference Pointer that points to a released memory location (in stack or in heap)

7 Heap (keko) (dynamic memory alloc.) Explicit usage (malloc etc) Programmer is responsible for memory allocation in C Memory fragmentation is possible free Improper or careless usage might leak memory Memory is a resource (like files) and it must also be managed

8 Variable definitions and scope of names #include <stdio.h> /* global variables here*/ double tulos; int main(int argc, char** argv) { /* Function s variables */ int i; for (i=0; i < 20; i++) { /* Block s variables*/ int j; j = i*4; } return 0; } Global variables Defined outside functions Visible to all functions that defined later in the code Maintains value through the whole program execution Internal variables (block, function) Defined at the beginning of the block Visible only within the block, not outside Maintains value only during single execution of block, not whole program Block anything within { }, also function

9 Refer to a name defined somewhere else > extern int i; static int si; extern int ei; void f() { int fi; static int sif; extern int eif; /* Avoid!*/ } void g(); static void h(); int eif; /* Definition here */ Definition is in - Some other file or library - Same file, but later Avoid usage!! Define variables as local as possible and at least within one file (if necessary, use the header file with macro protection)

10 Function s internal variable persistent and hidden -> static int i; static int si; extern int ei; void f() { int fi; static int sif; extern int eif; /* Avoid! */ } void g(); static void h(); int eif; /* Definition here */ With static definition the variable maintains its value from one execution time to the other. On the other hand, static limits the scope of the function (or variable). It cannot be used by functions in other files. (likejava sprivate)

11 Variable location in the memory / process s address space Extern informs compiler: Do not allocate space now. The allocation happes, where the definition is. Static informs compiler: Allocate space in heap instead of stack. The value has to be maintained, and that can only happen in heap area. Register informs compiler: Reserve a register for this if possible. The variable is used so much that memory access might slow down the execution. No specification = automatic allocation: global variables in heap during compilation, local variables in stack during execution

12 Function call stack The figure shows the stack when main has called function foo and the function has not yet returned Frame contains Function arguments Value of simple type Address of complex type Local variables SP stack pointer FP frame pointer Faculty of Science Department of Computer Science

13 Multidimensional arrays Liisa Marttinen & Tiina Niklander C programming

14 Reminder: Accessing arrays Type definitions: double arr[5]; /*static memory allocation*/ double *arr2; /* dynamic allocation with malloc */ Accessing array elements: *(arr + k) == arr [k] *(arr2+k) == arr2[k] *arr == arr [0] Liisa Marttinen & Tiina Niklander C programming

15 Multidimensional arrays Multidimensional arrays in C are actually single dimensional arrays with elements as arrays int t[3][2] = { {1,2},{11,12}, {21,22}}; for (i=0; i<3; i++) { for (j = 0; j<2; j++) printf ( t[%d][%d] = %d\,i,j, t[i][j]); putchar( \n ); } t[0][0] = 1 t[0][1] = 2 t[1][0] = 11 t[1][1] = 12 t[2][0] = 21 t[2][1] = 22 Liisa Marttinen & Tiina Niklander C programming

16 Two-dimensional array static char days [2][13] ={ {0, 31, 28, 31, 30, 31,30,31, 30, 31,30, 31}, {0, 31, 29, 31, 30, 31,30,31, 30, 31,30, 31} }; count = days[leap][2]; When leap ==0, then count = 28, when leap ==1, then count = 29 Liisa Marttinen & Tiina Niklander C programming

17 Array of pointers Liisa Marttinen & Tiina Niklander C programming

18 Pointer to array of pointers p double **p; Arrays of pointers to individual double elements Dereferencing has to be done twice **p Liisa Marttinen & Tiina Niklander C programming

19 Allocating space to array and the referenced elements Allocation for the array double **block; #define SIZE 3 if((block=calloc(size, sizeof(double*)))==null) error; for(i = 0; i < SIZE; i++) if((block[i]=calloc(1, sizeof(double)))==null) error; *(*block) = 2.1; block[0][0] = 2.1; Allocation for one element at a time Liisa Marttinen & Tiina Niklander C programming

20 Referencing the element and freeing them OR: bptr = block; for { **btr=2.1+i; bptr++; } Setting the values to the referenced elements for(i = 0; i < SIZE; i++) block[i][0] = i; Freeing the memory: referenced elements and pointer array Elements first for(i = 0; i < SIZE; i++) free(block[i]); free(block);..and then array block = NULL; Liisa Marttinen & Tiina Niklander C programming

21 kk joulu tammi helmi maalis syys loka marras huhti touko kesä elo invalid heinä Pointer arrays: array of strings String arrays are always pointer arrays, since each string is accessed via a pointer. char *monthfinnish(int k) { static char *kk[] = { invalid, tammi, helmi, maalis, huhti, touko, kesä, heinä, elo, syys, loka, marras, joulu }; return ( (k<1 k > 12)? kk[0] : kk[k] ); } Liisa Marttinen & Tiina Niklander C programming

22 Command-line arguments Liisa Marttinen & Tiina Niklander C programming

23 Command line arguments int main (int argc, char **argv); int main (int argc, char *argv[]); programname arg1 arg2 argc count of strings argv pointer to string array (contains argument values) echo Hello, world argc = 3 argv argv[0] argv[1] argv[2] echo\0 Hello,\0 world\0 echo Hello, world argc = 2 work in some systems! argv argv[0] argv[1] echo\0 Hello, world\0 Liisa Marttinen & Tiina Niklander C programming

24 Using command line arguments find Virtanen Ville regfile argc: 4 argv: argv[0] argv[1] argv[2] argv[3] find\0 Virtanen\0 Ville\0 regfile\0 argv[0] or argv contains 1. arg, that is the program name ( find ), argv[1] or argv+1 contains 2. argument ( Virtanen ) argv[2] or argv+2 contains 3. argument ( Ville ) argv[3] or argv+3 contains 4. argument ( regfile ) argv[0][0] or (*argv)[0] or **argv is the first character of the first arg ( f ) argv[2][4] or (*(argv+2))[4)] or *(*(argv+2)+4) is fifth char of third arg. Liisa Marttinen & Tiina Niklander C programming

25 Checking the number of arguments /* Check that count is correct*/ int main(int argc, char **argv) {. switch(argc) { case 4: /* all information on command line*/ case 3: /*OK! Use the preset file name*/ default: fprintf(stderr, Incorrect usage: %s.. \n", argv[0]); /*Would be better to inform correct usage*/ return EXIT_FAILURE; } Liisa Marttinen & Tiina Niklander C programming

26 Example program What does this program do? #include <stdio.h> /* Explaining comment removed */ int main(int argc, char** argv) { int i; for (i=0; i < argc; i++) printf( %s%s, argv[i], (i <argc-1)? : ); printf( \n ); return 0; } Liisa Marttinen & Tiina Niklander C programming

27 Example program: a.out print command line #include <stdio.h> /* Echo the command line with params */ int main(int argc, char** argv) { int i; for (i=0; i < argc; i++) printf( %s%s, argv[i], (i <argc-1)? : ); printf( \n ); return 0; } NOTICE: - Parameters - Array indexing Liisa Marttinen & Tiina Niklander argv: 0 a.out\0 print\0 command\0 line\0 Modification: How would you avoid printing the name of the program? C programming

28 Using command line arguments: Changing program behaviour with options name #define DEFAULT 10 #define MAX 80 /*Prints the n lines of the file to stdout*/ int display(const char *fname, int n, int Max); - = option; int main(int argc, char **argv) { int lines = DEFAULT; -n can be missing switch(argc) { case 3: /* process the number of lines option*/ if(argv[1][0]!= '-' sscanf(argv[1] + 1, "%d", &lines)!=1 lines <= 0) return EXIT_FAILURE; argv++; /* no break! Continues to case 2!!*/ case 2: if(display(argv[1], lines, MAX) == 0) return EXIT_FAILURE; break; default: return EXIT_FAILURE; } return EXIT_SUCCESS; } argv argv[0] argv[1] argv[2] show\0-20\0 testi\0 argv Number of lines show -n fname argv[0] argv[1] File name show\0 testi\0 Liisa Marttinen & Tiina Niklander C programming

29 Command line parameters: typical usage -options static int process_parameters(int argc, char *argv[]) { int i, string_found =0; for(i=1; i<argc; i++){ /* process command switches. Note side effects! */ if (argv[i][0] == '-') { switch (argv[i][1]) { options: -c, -i, and -b case 'c': count_lines = TRUE; break; case 'i': ignore_case = TRUE; break; case 'b : line_beginning = TRUE; break; default: printf("unknown option %s - ignored \n", argv[i]); break; }} else { Search string cannot start with character - if (!string_found) { copy(string, argv[i], STRINGSIZE); string_found =1; } else{ printf("only one search string! \n"); return FALSE; } }} if (!string_found) { Functions always return value! printf("the search string must be given!\n"); return FALSE; } return TRUE; Liisa Marttinen } & Tiina Niklander C programming

30 Advanced aspects of C operators Faculty of Science Department of Computer Science

31 Assignment combinations t /= n -= m *= k += 7; Assignment-combination operators have low precedence are associated from right to left So in the above code fragment k = k+7 is evaluated first m = m*k is next n = n-m then and t = t /n is the last one Faculty of Science Department of Computer Science

32 Lazy evaluation When evaluating a condition operation evaluate the first (left-most) operator If condition result already known, second operator is not evaluated : first is true, second not evaluated && : first is false, second not evaluated When skip, always skip the second operand! Müldner calls this feature short-circuit evaluation rule Faculty of Science Department of Computer Science

33 Lazy evaluation y = a < 10 a >= 2 * b && b!= 1; Evaluation order of this example: First operator: a < 10 and second a >= 2 * b && b!= 1 If a = 7 -> skip the second and y = 1 If a = 17 and b = 20 start evaluating the first part of second operator result: skip second part b!=1 and y = 0 NOTE: The evaluation order is from left to right (and it does not follow the precedence) Faculty of Science Department of Computer Science

34 Lazy evaluation: guarding if ((x!= 0) && (total / x < minimum)) if ((ptr!= NULL) && (ptr->next == NULL)) Faculty of Science Department of Computer Science

35 Lazy evaluation y = a < 0 a > b && b > c b > 10; Which parts will be evaluated/skipped when (and what is the result) a = -3, b =17, c = 6 a = 17, b= 17, c = 17 a = 15, b = 11, c = 9 a = 12, b = 9, c = 6 Faculty of Science Department of Computer Science

36 What if you have: y = a < 0 a > b && b > c b++ > 10; How would you make sure that b gets incremented correctly! This could cause errors, if you assume that b is always incremented!! b would be incremented only when, its value is between a and c and a is positive. Recommendation: Avoid increment and decrement with complex condition operations Faculty of Science Department of Computer Science

37 Some aspects of numerical calculations (Not C specific, but more general) Faculty of Science Department of Computer Science

38 Choosing the proper data type Integer or real? - in most cases obvious Float vs. double can be combined freely in expressions degree of precision required for the data dictates the use of double all math.h functions use double - easier to use double float uses less space (half of the space of double) Integer calculations are faster that real calculations, float calculations faster than double calculations Faculty of Science Department of Computer Science

39 Value range For integers: signed, unsigned, short and long. Max short signed: Max long signed: Max long unsigned: For float the minimum value range is 1.175E E For double: 2.225E E Faculty of Science Department of Computer Science

40 Representation error float and double are approximate representations, but with differing precision. Consider the code below: float w = 4.4; double x = 4.4; printf(" Is x == (double) w? %i \n", (x == (double)w) ); printf(" Is (float)x == w? %i \n", ((float)x == w) ); The output may be unexpected, if you forgot that the two numbers are represented with limited, and different, precision and that the == operator tests for exact bit-by-bit equality: Is x == (double)w? 0 Is (float)x == w? 1 Faculty of Science Department of Computer Science

41 Representation error Explanation: When a more-precise value is cast to the less-precise type, the extra bits are truncated and the numbers are exactly equal. When a shorter value is cast to the longer type, it is lengthened by adding zero bits at the end of the mantissa, not by recomputing the additional bit values. In general, these zeros are not equal to the meaningful bits in the double value. Faculty of Science Department of Computer Science

42 Representation error float w; double x, y = 11.0, z = 9.0; x = z * (y / z); w = y-x; The result is as expected, w = 0, x = However, change the starting values y = 15.0 and z = 11.0, and the result is w = e 15, x = Why? small precision and truncation error in calculations Faculty of Science Department of Computer Science

43 Comparing floating point numbers bit-by-bit comparison does not work. The precision might be different in two calculated values Compare difference of two numbers to a preset epsilon value. double epsilon = 1.0e-3; double number, target; if (fabs( number -target) < epsilon) /* then we consider that number == target */ else /* we consider the values different; */ Faculty of Science Department of Computer Science

44 Overflow / underflow Integer overflow value wraps from large positive to large negative (or vise versa) could be potential security hole Floating point overflow special bit pattern, called infinity, used in overflow HUGE_VAL (in math.h) is this infinity value Floating point underflow magnitude of the number falls below the smallest number in the representable range 0 exponent and a nonzero mantissa, denormalized Faculty of Science Department of Computer Science

45 Order of magnitude and other problems If you add a small float number to a large one, and their exponents differ by more than 107, the addition likely will have no effect. The answer will be the same large number that you started with. A special value called NaN, which stands for not a number, can be generated through operations such as 0/0. This is another special bit pattern that does not correspond to a real value. The IEEE standard defines that any further operation attempted using a NaN or Infinity as an operand will return the same value. Faculty of Science Department of Computer Science

Some Details of C and C Environment

Some Details of C and C Environment Some Details of C and C Environment In this last lecture, we look at Bit orders and storage alignment, Advanced aspects of C operators, and Some aspects of numerical calculations. () 7. lokakuuta 2012

More information

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

C Introduction. Comparison w/ Java, Memory Model, and Pointers

C Introduction. Comparison w/ Java, Memory Model, and Pointers CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language

More information

Programming in C First meeting Tiina Niklander

Programming in C First meeting Tiina Niklander Programming in C First meeting 5.9.2016 Tiina Niklander Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 1 Learning goal objectives Language structures, data structures, modules,

More information

Lecture 3: C Programm

Lecture 3: C Programm 0 3 E CS 1 Lecture 3: C Programm ing Reading Quiz Note the intimidating red border! 2 A variable is: A. an area in memory that is reserved at run time to hold a value of particular type B. an area in memory

More information

CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014)

CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014) CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014) Goals Demonstrate proficiency in the use of the switch construct and in processing parameter data passed to a program via the command

More information

CSE 333 Lecture 2 Memory

CSE 333 Lecture 2 Memory CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking

More information

Programming in C First meeting

Programming in C First meeting Programming in C First meeting 8.9.2016 Tiina Niklander Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 1 Course structure Weekly exercise deadline on Wednesday, lectures

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

Memory Allocation in C

Memory Allocation in C Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called

More information

Data types, arrays, pointer, memory storage classes, function call

Data types, arrays, pointer, memory storage classes, function call Data types, arrays, pointer, memory storage classes, function call Jan Faigl Department of Computer Science Faculty of Electrical Engineering Czech Technical University in Prague Lecture 03 BE5B99CPL C

More information

Technical Questions. Q 1) What are the key features in C programming language?

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

Programming in C - Part 2

Programming in C - Part 2 Programming in C - Part 2 CPSC 457 Mohammad Reza Zakerinasab May 11, 2016 These slides are forked from slides created by Mike Clark Where to find these slides and related source code? http://goo.gl/k1qixb

More information

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 { Memory A bit is a binary digit, either 0 or 1. A byte is eight bits, and can thus represent 256 unique values, such as 00000000 and 10010110. Computer scientists often think in terms of hexadecimal, rather

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( ) Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Winter 2009 Lecture 7 Introduction to C: The C-Level of Abstraction CSE 303 Winter 2009, Lecture 7 1 Welcome to C Compared to Java, in rough

More information

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function Grade: / 20 Lab Exam 1 D500 1. [1 mark] Give an example of a sample input which would make the function scanf( "%f", &f ) return 0? Answer: Anything that is not a floating point number such as 4.567 or

More information

Variation of Pointers

Variation of Pointers Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before

More information

These are reserved words of the C language. For example int, float, if, else, for, while etc.

These are reserved words of the C language. For example int, float, if, else, for, while etc. Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

More information

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga Arrays and Strings Antonio Carzaniga Faculty of Informatics Università della Svizzera italiana February 23, 2015 Outline General memory model Definition and use of pointers Invalid pointers and common

More information

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment. Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special

More information

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University ECEN 449 Microprocessor System Design Review of C Programming 1 Objectives of this Lecture Unit Review C programming basics Refresh programming skills 2 Basic C program structure # include main()

More information

Computer System and programming in C

Computer System and programming in C 1 Basic Data Types Integral Types Integers are stored in various sizes. They can be signed or unsigned. Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14 BIL 104E Introduction to Scientific and Engineering Computing Lecture 14 Because each C program starts at its main() function, information is usually passed to the main() function via command-line arguments.

More information

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3). cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011 Two s Complement Review CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part I) Instructor: Michael Greenbaum http://inst.eecs.berkeley.edu/~cs61c/su11 Suppose we had

More information

Programming in C week 1 meeting Tiina Niklander

Programming in C week 1 meeting Tiina Niklander Programming in C week 1 meeting 2.9.2015 Tiina Niklander Faculty of Science Department of Computer Science 3.9.2015 1 Course structure Based on C programming course in Aalto, but with some exercises created

More information

ECEN 449 Microprocessor System Design. Review of C Programming

ECEN 449 Microprocessor System Design. Review of C Programming ECEN 449 Microprocessor System Design Review of C Programming 1 Objectives of this Lecture Unit Review C programming basics Refresh es programming g skills s 2 1 Basic C program structure # include

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays and Pointers (part 2) Be extra careful with pointers! Arrays and Pointers (part 2) EECS 2031 22 October 2017 1 Be extra careful with pointers! Common errors: l Overruns and underruns Occurs when you reference a memory beyond what you allocated. l Uninitialized

More information

FORM 2 (Please put your name and form # on the scantron!!!!)

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function

More information

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays and Pointers (part 2) Be extra careful with pointers! Arrays and Pointers (part 2) CSE 2031 Fall 2011 23 October 2011 1 Be extra careful with pointers! Common errors: Overruns and underruns Occurs when you reference a memory beyond what you allocated. Uninitialized

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016 Malloc Lab & Midterm Solutions Recitation 11: Tuesday: 11/08/2016 Malloc 2 Important Notes about Malloc Lab Malloc lab has been updated from previous years Supports a full 64 bit address space rather than

More information

Programming Language Implementation

Programming Language Implementation A Practical Introduction to Programming Language Implementation 2014: Week 10 Garbage Collection College of Information Science and Engineering Ritsumeikan University 1 review of last week s topics dynamic

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 12: Memory, Files and Bitoperations (pronobis@kth.se) Overview Overview Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations Wrap Up Lecture

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below: QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

REMEMBER TO REGISTER FOR THE EXAM.

REMEMBER TO REGISTER FOR THE EXAM. REMEMBER TO REGISTER FOR THE EXAM http://tenta.angstrom.uu.se/tenta/ Floating point representation How are numbers actually stored? Some performance consequences and tricks Encoding Byte Values Byte =

More information

Floating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754

Floating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754 Floating Point Puzzles Topics Lecture 3B Floating Point IEEE Floating Point Standard Rounding Floating Point Operations Mathematical properties For each of the following C expressions, either: Argue that

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one

More information

Memory Corruption 101 From Primitives to Exploit

Memory Corruption 101 From Primitives to Exploit Memory Corruption 101 From Primitives to Exploit Created by Nick Walker @ MWR Infosecurity / @tel0seh What is it? A result of Undefined Behaviour Undefined Behaviour A result of executing computer code

More information

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Data Types Basic Types Enumerated types The type void Derived types

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 2: Numbers & C Language Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Numbers wrap-up This is not on the exam! Break C Primer Administrivia,

More information

Floating Point (with contributions from Dr. Bin Ren, William & Mary Computer Science)

Floating Point (with contributions from Dr. Bin Ren, William & Mary Computer Science) Floating Point (with contributions from Dr. Bin Ren, William & Mary Computer Science) Floating Point Background: Fractional binary numbers IEEE floating point standard: Definition Example and properties

More information

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion CS 61C: Great Ideas in Computer Architecture Lecture 2: Numbers & C Language Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Numbers wrap-up This is not on the exam! Break C Primer Administrivia,

More information

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee ECE 250 / CS 250 Computer Architecture C to Binary: Memory & Data Representations Benjamin Lee Slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Administrivia

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

COMP2611: Computer Organization. Data Representation

COMP2611: Computer Organization. Data Representation COMP2611: Computer Organization Comp2611 Fall 2015 2 1. Binary numbers and 2 s Complement Numbers 3 Bits: are the basis for binary number representation in digital computers What you will learn here: How

More information

High Performance Computing MPI and C-Language Seminars 2009

High Performance Computing MPI and C-Language Seminars 2009 High Performance Computing - Seminar Plan Welcome to the High Performance Computing seminars for 2009. Aims: Introduce the C Programming Language. Basic coverage of C and programming techniques needed

More information

Review Topics. Final Exam Review Slides

Review Topics. Final Exam Review Slides Review Topics Final Exam Review Slides!! Transistors and Gates! Combinational Logic! LC-3 Programming!! Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox,

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Introduction to C, Pointers June 24, 2014 Review of Last Lecture Six Great Ideas in Computer Architecture Number Representation Bits can represent anything! n bits can represent up to 2 n things Unsigned,

More information

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CPSC 3740 Programming Languages University of Lethbridge. Data Types Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura CS 2060 Week 6 1 Pointer Variables 2 Pass-by-reference 3 const pointers 4 Pointer arithmetic 5 sizeof 6 Arrays of pointers 7 Next Time Pointers The pointer is one of C s most powerful and important features.

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #8 Feb 27 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline More c Preprocessor Bitwise operations Character handling Math/random Review for midterm Reading: k&r ch

More information

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Foundations of Computer Systems

Foundations of Computer Systems 18-600 Foundations of Computer Systems Lecture 4: Floating Point Required Reading Assignment: Chapter 2 of CS:APP (3 rd edition) by Randy Bryant & Dave O Hallaron Assignments for This Week: Lab 1 18-600

More information

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities

More information

Systems Programming and Computer Architecture ( )

Systems Programming and Computer Architecture ( ) (252-0061-00) Session 9 Floating Point Systems Group Department of Computer Science ETH Zürich 1 Floating Point Recap for the Assignment 2 Floating Point Representation Numerical Form Scientific Notation

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

3.5 Floating Point: Overview

3.5 Floating Point: Overview 3.5 Floating Point: Overview Floating point (FP) numbers Scientific notation Decimal scientific notation Binary scientific notation IEEE 754 FP Standard Floating point representation inside a computer

More information

Procedures, Parameters, Values and Variables. Steven R. Bagley

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14 APT Session 4: C Laurence Tratt Software Development Team 2017-11-10 1 / 14 http://soft-dev.org/ What to expect from this session 1 C. 2 / 14 http://soft-dev.org/ Prerequisites 1 Install either GCC or

More information

Final CSE 131B Spring 2004

Final CSE 131B Spring 2004 Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)

More information

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CprE 288 Introduction to Embedded Systems Exam 1 Review.  1 CprE 288 Introduction to Embedded Systems Exam 1 Review http://class.ece.iastate.edu/cpre288 1 Overview of Today s Lecture Announcements Exam 1 Review http://class.ece.iastate.edu/cpre288 2 Announcements

More information

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False.

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False. Quiz 0 Answer Key Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d True or False. 6. T or F 7. T 8. F 9. T 10. T or F Itching for Week 0? 11. 00011001 + 00011001

More information

CS 0449 Sample Midterm

CS 0449 Sample Midterm Name: CS 0449 Sample Midterm Multiple Choice 1.) Given char *a = Hello ; char *b = World;, which of the following would result in an error? A) strlen(a) B) strcpy(a, b) C) strcmp(a, b) D) strstr(a, b)

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

5.Coding for 64-Bit Programs

5.Coding for 64-Bit Programs Chapter 5 5.Coding for 64-Bit Programs This chapter provides information about ways to write/update your code so that you can take advantage of the Silicon Graphics implementation of the IRIX 64-bit operating

More information

CSC 2400: Computer Systems. Arrays and Strings in C

CSC 2400: Computer Systems. Arrays and Strings in C CSC 2400: Computer Systems Arrays and Strings in C Lecture Overview Arrays! List of elements of the same type Strings! Array of characters ending in \0! Functions for manipulating strings 1 Arrays: C vs.

More information

Lecture 07 Debugging Programs with GDB

Lecture 07 Debugging Programs with GDB Lecture 07 Debugging Programs with GDB In this lecture What is debugging Most Common Type of errors Process of debugging Examples Further readings Exercises What is Debugging Debugging is the process of

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

6.S096 Lecture 2 Subtleties of C

6.S096 Lecture 2 Subtleties of C 6.S096 Lecture 2 Subtleties of C Data structures and Floating-point arithmetic Andre Kessler January 10, 2014 Andre Kessler 6.S096 Lecture 2 Subtleties of C January 10, 2014 1 / 17 Outline 1 Memory Model

More information

Chapter 10 Memory Model for Program Execution. Problem

Chapter 10 Memory Model for Program Execution. Problem Chapter 10 Memory Model for Program Execution Original slides by Chris Wilcox, Colorado State University Problem How do we allocate memory during the execution of a program written in C?! Programs need

More information

Array Initialization

Array Initialization Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]

More information

Systems Programming and Computer Architecture ( )

Systems Programming and Computer Architecture ( ) Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture (252-0061-00) Timothy Roscoe Herbstsemester 2016 1 4: Pointers Computer Architecture and Systems Programming

More information

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

CSE2003: System Programming (Spring 2010) Programming Assignment #1: Adding floating-point numbers. Due: April 11, 11:59PM

CSE2003: System Programming (Spring 2010) Programming Assignment #1: Adding floating-point numbers. Due: April 11, 11:59PM CSE2003: System Programming (Spring 2010) Programming Assignment #1: Adding floating-point numbers Due: April 11, 11:59PM 1. Introduction In this assignment, you are required to implement a function in

More information

Time: 8:30-10:00 pm (Arrive at 8:15 pm) Location What to bring:

Time: 8:30-10:00 pm (Arrive at 8:15 pm) Location What to bring: ECE 120 Midterm 1 HKN Review Session Time: 8:30-10:00 pm (Arrive at 8:15 pm) Location: Your Room on Compass What to bring: icard, pens/pencils, Cheat sheet (Handwritten) Overview of Review Binary IEEE

More information

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

COMP26120: Pointers in C (2018/19) Lucas Cordeiro COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information