Introduction to Systems Programming - COMP 1002, 1402

Size: px
Start display at page:

Download "Introduction to Systems Programming - COMP 1002, 1402"

Transcription

1 POINTERS Introduction to Systems Programming - COMP 1002, 1402

2 Outline Memory Allocation Pointers in C Pointer and addresses Pointer Arithmetic Dynamic Memory Allocation

3 Memory Allocation When you declare a variable, some memory is allocated to store the value of the variable. When you declare a global variable, the memory that is allocated for the global variable is permanent throughout the program. When you declare a local variable inside a function, then the memory allocated for the local variable exists in a part of memory called the stack, and it exists only for as long as the function is being called. Same for parameters to a function.

4 Declaring Pointers in C 4 int *p; a pointer to an int double *q; a pointer to a double char **r; type *s; a pointer to a pointer to a char a pointer to an object of type type E.g, a struct, union, function, something defined by a typedef, etc.

5 Declaring Pointers in C (continued) 5 Pointer declarations: read from right to left const int *p; p is a pointer to an integer constant I.e., pointer can change, thing it points to cannot int * const q; q is a constant pointer to an integer variable I.e., pointer cannot change, thing it points to can! const int * const r; r is a constant pointer to an integer constant

6 Pointers in C 6 Used everywhere For building useful, interesting, data structures For returning data from functions For managing arrays '&' unary operator generates a pointer to x E.g., scanf("%d", &x); E.g., p = &c; Operand of '&' must be an l-value i.e., a legal object on left of assignment operator ('=') Unary '*' operator dereferences a pointer i.e., gets value pointed to E.g. *p refers to value of c (above) E.g., *p = x + y; *p = *q;

7 Pointers and Addresses C allows you to get the address of a variable. C has a type called pointer that points to another type, such as int, unsigned char, float etc. So, in C, there is an int pointer, unsigned char pointer etc. A pointer to an integer is used to contain the address of an integer. int n; // declare an integer variable called n int * iptr; // declare a variable called iptr // this variable is a pointer to an integer void func() { iptr = &n; // set the value of iptr to the address of variable n

8 Pointer and Address Example Here, we show the address and content of the variables n and iptr as they are declared. After calling the function, the content at Address 101 will be the value 100. Variable Address Content n iptr int n = 20; // declare an integer variable called n int * iptr = 0; // declare a variable called iptr // this variable is a pointer to an integer void func() { iptr = &n; // set the value of iptr to the address of variable n

9 The & Operator As you saw in the preceding slide, the & operator is used to get the address of a variable. Here are some more examples. int n = 20; int * iptr = 0; float f = 1.05; float * fptr = &f; Variable Address Content n iptr f fptr void func() { iptr = &n; // set the value of iptr to the address of variable n

10 The * Operator: Dereferencing a Pointer You can get the contents of what the pointer is pointing to by dereferencing a pointer. int n = 20; int * iptr = 0; int i; void func() { iptr = &n; i = *iptr + 50;

11 Exercise: What gets printed? Address int i; #include <stdio.h> int n = 20; float f = 1.05; float * fptr = &f; int * iptr = 0; int i; int main() { iptr = &n; printf("addresses %d %d\n", iptr, fptr); printf("values %d %f\n", *iptr, *fptr); i = *iptr + 50; *iptr = 10; printf("values %d %d\n", n, i); return 0;

12 Dereferencing Pointer Dereferencing pointer actually refers to the contents of what the pointer is pointing to. This doesn t simply refer to the value. Hence, the content can be changed! #include <stdio.h> int n = 20; int * iptr = 0; int main() { iptr = &n; *iptr = 10; printf("values %d\n", n); return 0;

13 Call by Pointer Contrast the following functions One is call by value, the other is call by pointer. What exactly happens when those functions are called? #include <stdio.h> int n = 20; void func1(int i) { i = i + 10; void func2(int *r) { *r = *r + 20; int main() { func1(n); printf( n is %d\n", n); func2(&n); printf( n is %d\n", n); return 0;

14 Can pointer refer to invalid address? Yes, you can set pointer to any value you want. But, if you set it to some reserved address, then the program will crash when you re trying to refer to the reserved address. int i; int *iptr; int main() { iptr = (int *)500; i = *iptr + 50; Set to invalid address 500 (probably reserved by the operating system) Program crashes when trying to reference invalid address.

15 Pointer Arithmetic 15 int *p, *q; q = p + 1; Construct a pointer to the next integer after *p and assign it to q double *p, *r; int n; r = p + n; Construct a pointer to a double that is n doubles beyond *p, and assign it to r n may be negative

16 Pointer Arithmetic (continued) 16 long int *p, *q; p++; q--; Increment p to point to the next long int; decrement q to point to the previous long int float *p, *q; int n; n = p q; n is the number of floats between *p and *q; i.e., what would be added to q to get p

17 Pointer Arithmetic (continued) 17 long int *p, *q; p++; q--; Increment p to point to the next long int; decrement q to point to the previous long int float *p, *q; int n; n = p q; n is the number of floats between *p and *q; i.e., what would be added to q to get p

18 The new function void func( ) { int *iptr; iptr = new int(15); Refer to the highlighted line above. The new function does the following: Allocate memory in the part of memory called heap. The amount of memory allocated is the amount needed to contain one integer. The content of the memory location is set to the integer 15. new returns the address of the memory that has just been allocated.

19 The delete function The delete function frees the memory that has been created by new. Traditionally, C uses the functions malloc and free, but I don t like them. These days, we use the functions new and delete because they are cleaner. void func( ) { int *iptr; iptr = new int(15); delete iptr; iptr = new int(20);

20 malloc and free void * malloc ( size_t size ); void free ( void * ptr ); malloc requests some memory from the Operation System and returns the address of the memory allocated. free frees up the space previously received by malloc. void func(int n) { int i; int *iptr; iptr = (int *)malloc(n*sizeof(int)); for (i=0;i<n;i++) { iptr[i] = 15 + i * 2; free(iptr);

21 Pointer Example Program: Normalize (Part 1) Example: The normalize function to normalize a vector Mathematical background: Given a 3D vector V = (x,y,z), the magnitude of the vector V is sqrt(x*x+y*y+z*z) Normalizing a vector means to make the vector the same direction as before, but with unit length (that is, the magnitude of the normalized vector should be 1). void Normalize(float *x, float *y, float *z) { float mag; mag = (*x) * (*x) + (*y) * (*y) + (*z) * (*z); mag = sqrt(mag); // at the beginning of source file, need #include <math.h> // to use the function sqrt *x = (*x) / mag; *y = (*y) / mag; *z = (*z) / mag;

22 Pointer Example Program: Normalize (Part 2) Here, we use the Normalize function to change the values of a, b, c. The Normalize function can be used to change the values of other variables. This is a good use of pointers as parameters, because they can change the values of the contents they refer to. int main() { float a, b, c; a = 10.0; b = 20.0; c = 15.0; Normalize(&a, &b, &c); printf( vector is %f %f %f\n, a, b, c); return 0;

23 The NULL Pointer malloc returns the address of the memory that has been allocated. However, sometimes it fails. For example, when the heap is full, or when malloc requests too much memory, the OS cannot give malloc the memory. In this case, the return value of malloc is the NULL pointer. void func(int n) { void func(int n) { int i; int *iptr; iptr = (int *)malloc(n*sizeof(int)); if (iptr!= 0) { // check that malloc did not return the NULL pointer for (i=0;i<n;i++) { iptr[i] = 15 + i * 2; free(iptr);

24 What is the relationship between array and pointer? 24 Arrays and pointers are closely related in C In fact, they are essentially the same thing! Esp. when used as parameters of functions int A[10]; int *p; Type of A is int * p = A; and A = p; are legal assignments *p refers to A[0] *(p + n) refers to A[n] p = &A[5]; is the same as p = A + 5;

25 Arrays and Pointers (continued) 25 double A[10]; vs. double *A; Only difference: double A[10] sets aside ten units of memory, each large enough to hold a double, and A is initialized to point to the zeroth unit. double *A sets aside one pointer-sized unit of memory, not initialized You are expected to come up with the memory elsewhere! Note: all pointer variables are the same size in any given machine architecture Regardless of what types they point to

26 Array and Address When you declare an array, the name of the array also refers to the address of its first element. In the following example, the value of n is the same as the value of &(n[0]) int n[20]; // declare an array of 20 integers void func() { if (n==&(n[0])) { printf( they are the same\n );

27 Array and Pointer Since the name of an array is the same as an address, and a pointer is also the same as an address, a pointer can be set to an array. However, do not set array to pointer. int n[20]; // declare an array of 20 integers int *iptr; void func() { iptr = n; // set pointer to array n[0] = 5; printf( %d, *iptr); // n = iptr; // do not set array to pointer

28 Treating Pointer as Array int n[20]; // declare an array of 20 integers int *iptr; void func() { iptr = n; // set pointer to array for (i=0;i<20;i++) { iptr[i] = 5; // treat pointer as array for (i=0;i<20;i++) { printf( %d, n[i]);

29 Example: Average float fg[80]; float GetAverage(float *marray, int len) { int i; float sum; sum = 0; for (i=0;i<len;i++) { sum += marray[i]; return sum/(float)len; int main( ) { float f1[120]; float f2[60]; float a, b, c; // some code to set the values of f1, f2 and fg a = GetAverage(f1,120); b = GetAverage(f2,60); c = GetAverage(fg,80); return 0;

30 new and delete for Arrays We learned that new can be used to allocate space for an int, float etc. We learned that delete is used to free the space. Now, new can be used to allocate an entire array, and delete is used to free the entire array. void func() { int *iptr; iptr = new int[20]; delete [ ] iptr;

31 Example: Creating a new array // print 1! up to n! 2000 times void printfactorials(int n) { int *iptr; int i, j; iptr = new int[n]; // create an array of length n iptr[0] = 1; for (i=1;i<n;i++) { iptr[i] = iptr[i-1] * (i+1); // set each element of the array for (i=0;i<2000;i++) { for (j=0;j<n;j++) { printf( %d, iptr[j]); printf( \n ); delete [ ] iptr; // free the memory

32 Exercise: Delete Duplicates Write a function DeleteDuplicates This function receives an array arr as an argument, and an integer len, that tells the length of the array. The array received as argument has been allocated by new. The argument array contains floating point numbers in non-decreasing order. DeleteDuplicates should create a new array, except that this array should contain no duplicates. DeleteDuplicates should return the address of this new array. DeleteDuplicates should free the memory used by the old array. The length of the new array is set in nlen. float *DeleteDuplicates(float *arr, int len, int *nlen); // function declaration void func() { // example of use float *eptr; int nlen; eptr = new float[5]; eptr[0] = 1.0; eptr[1] = 1.6; eptr[2] = 1.6; eptr[3] = 2.3; eptr[4] = 2.3; eptr = DeleteDuplicates(eptr,5, &nlen);

33 Note 33 C does not assign arrays to each other E.g, double A[10]; double B[10]; A = B; assigns the pointer value B to the pointer value A Original contents of array A are untouched (and possibly unreachable!)

34 Arrays as Function Parameters 34 void init(float A[], int arraysize); void init(float *A, int arraysize); Are identical function prototypes! Pointer is passed by value I.e. caller copies the value of a pointer to float into the parameter A Called function can reference through that pointer to reach thing pointed to

35 Arrays as Function Parameters (continued) 35 void init(float A[], int arraysize){ int n; for(n = 0; n < arraysize; n++) A[n] = (float)n; //init Assigns values to the array A in place So that caller can see the changes!

36 Examples 36 while ((rc = scanf("%lf", &array[count]))!=eof && rc!=0) double getlargest(const double A[], const int sizea) { double d; if (sizea > 0) { d = getlargest(&a[1], sizea-1); return (d > A[0])? d : A[0]; else return A[0]; // getlargest

37 Result 37 Even though all arguments are passed by value to functions pointers allow functions to assign back to data of caller Arrays are pointers passed by value

38 Exercise: Reverse There is an array of integers int a[100]; Assume that the array contains some numbers. Reverse the array. In other words, after you run your code, the first element should contain the last element, and vice versa. And, the second element should contain the next to last element etc. int a[100]; int main() { Fill in code here

39 Exercise: Change Write a function CalculateChange(int m) that prints the change for a money value. For example CalculateChange(115) should print The valid coin values are 1, 5, 10 and 25.

40 Review: Pointers What does the following program print? #include <stdio.h> Memory: int main() { int i, j; Variable Address Content int *iptr; i 1000? j 1001? i = 256; iptr 5000? iptr = &i; printf( %d, (int)iptr); printf( %d, *iptr); iptr = (int *)i; printf( %d, (int)iptr); return 0;

41 Review: Pointers Answer of previous page: Which line(s) may cause compile time error? #include <stdio.h> int main() { int i, j; int *iptr; i = 256; iptr = 512; iptr = &i; iptr = (int *)i; *iptr = 20; j = iptr; j = &iptr; j = (int) &iptr; &i = iptr; return 0;

42 Review: Pointers Answer of previous page: Lines 7, 13, 14 and 17 Which line(s) may cause the program to crash at runtime? #include <stdio.h> int main() { int i, j; int *iptr; int *jptr; i = 256; iptr = (int *)512; jptr = iptr; i = *iptr + 10; iptr = (int *)i; *iptr = 20; return 0;

43 Review: new and delete Answer of previous page: Lines 12 and 15 Which line(s) may cause compile time error? Which line(s) may cause program to crash at run time? #include <stdio.h> int main() { int i; int *iptr; i = 10; iptr = new int(5); *iptr = 20; delete iptr; *iptr = 15; iptr = &i; delete iptr; return 0; Answer : Line 13 may cause a problem because you write to memory that has been freed. Line 16 has an error because you try to free memory from the stack, i.e. not created by new.

44 QUESTIONS? 44

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure Short Notes on Dynamic Memory Allocation, Pointer and Data Structure 1 Dynamic Memory Allocation in C/C++ Motivation /* a[100] vs. *b or *c */ Func(int array_size) double k, a[100], *b, *c; b = (double

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists Lecture 11 Doubly Linked Lists & Array of Linked Lists In this lecture Doubly linked lists Array of Linked Lists Creating an Array of Linked Lists Representing a Sparse Matrix Defining a Node for a Sparse

More information

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example Announcements Memory management Assignment 2 posted, due Friday Do two of the three problems Assignment 1 graded see grades on CMS Lecture 7 CS 113 Spring 2008 2 Safe user input If you use scanf(), include

More information

GDB Tutorial. A Walkthrough with Examples. CMSC 212 - Spring 2009. Last modified March 22, 2009. GDB Tutorial

GDB Tutorial. A Walkthrough with Examples. CMSC 212 - Spring 2009. Last modified March 22, 2009. GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 What is gdb? GNU Debugger A debugger for several languages, including C and C++ It allows you to inspect what the program

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer. Coding Rules Section A: Linux kernel style based coding for C programs Coding style for C is based on Linux Kernel coding style. The following excerpts in this section are mostly taken as is from articles

More information

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Dr. Martin O. Steinhauser University of Basel Graduate Lecture Spring Semester 2014 Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Friday, 7 th March

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer About The Tutorial C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

5 Arrays and Pointers

5 Arrays and Pointers 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

More information

IC4 Programmer s Manual

IC4 Programmer s Manual IC4 Programmer s Manual Charles Winton 2002 KISS Institute for Practical Robotics www.kipr.org This manual may be distributed and used at no cost as long as it is not modified. Corrections to the manual

More information

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11 Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11 In this lab, you will first learn how to use pointers to print memory addresses of variables. After that, you will learn

More information

Chapter 13 Storage classes

Chapter 13 Storage classes Chapter 13 Storage classes 1. Storage classes 2. Storage Class auto 3. Storage Class extern 4. Storage Class static 5. Storage Class register 6. Global and Local Variables 7. Nested Blocks with the Same

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

CP Lab 2: Writing programs for simple arithmetic problems

CP Lab 2: Writing programs for simple arithmetic problems Computer Programming (CP) Lab 2, 2015/16 1 CP Lab 2: Writing programs for simple arithmetic problems Instructions The purpose of this Lab is to guide you through a series of simple programming problems,

More information

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE PROGRAMMING IN C CONTENT AT A GLANCE 1 MODULE 1 Unit 1 : Basics of Programming Unit 2 : Fundamentals Unit 3 : C Operators MODULE 2 unit 1 : Input Output Statements unit 2 : Control Structures unit 3 :

More information

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012 7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012 October 17 th, 2012. Rules For all problems, read carefully the input and output session. For all problems, a sequential implementation is given,

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

Lecture 12 Doubly Linked Lists (with Recursion)

Lecture 12 Doubly Linked Lists (with Recursion) Lecture 12 Doubly Linked Lists (with Recursion) In this lecture Introduction to Doubly linked lists What is recursion? Designing a node of a DLL Recursion and Linked Lists o Finding a node in a LL (recursively)

More information

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell C Dynamic Data Structures University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell Data Structures A data structure is a particular organization of data in memory. We want to

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Real Application Design Christian Nastasi http://retis.sssup.it/~lipari http://retis.sssup.it/~chris/cpp Scuola Superiore Sant Anna Pisa April 25, 2012 C. Nastasi (Scuola

More information

6.S096 Lecture 1 Introduction to C

6.S096 Lecture 1 Introduction to C 6.S096 Lecture 1 Introduction to C Welcome to the Memory Jungle Andre Kessler Andre Kessler 6.S096 Lecture 1 Introduction to C 1 / 30 Outline 1 Motivation 2 Class Logistics 3 Memory Model 4 Compiling 5

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint) TN203 Porting a Program to Dynamic C Introduction Dynamic C has a number of improvements and differences compared to many other C compiler systems. This application note gives instructions and suggestions

More information

Chapter 7D The Java Virtual Machine

Chapter 7D The Java Virtual Machine This sub chapter discusses another architecture, that of the JVM (Java Virtual Machine). In general, a VM (Virtual Machine) is a hypothetical machine (implemented in either hardware or software) that directly

More information

ECS 165B: Database System Implementa6on Lecture 2

ECS 165B: Database System Implementa6on Lecture 2 ECS 165B: Database System Implementa6on Lecture 2 UC Davis, Spring 2011 Por6ons of slides based on earlier ones by Raghu Ramakrishnan, Johannes Gehrke, Jennifer Widom, Bertram Ludaescher, and Michael Gertz.

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

C Interview Questions

C Interview Questions http://techpreparation.com C Interview Questions And Answers 2008 V i s i t T e c h P r e p a r a t i o n. c o m f o r m o r e i n t e r v i e w q u e s t i o n s a n d a n s w e r s C Interview Questions

More information

MISRA-C:2012 Standards Model Summary for C / C++

MISRA-C:2012 Standards Model Summary for C / C++ MISRA-C:2012 Standards Model Summary for C / C++ The LDRA tool suite is developed and certified to BS EN ISO 9001:2000. This information is applicable to version 9.4.2 of the LDRA tool suite. It is correct

More information

Data Structure with C

Data Structure with C Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which

More information

Stack Allocation. Run-Time Data Structures. Static Structures

Stack Allocation. Run-Time Data Structures. Static Structures Run-Time Data Structures Stack Allocation Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers,

More information

Introduction to Information Security

Introduction to Information Security Introduction to Information Security 0368-3065, Spring 2015 Lecture 1: Introduction, Control Hijacking (1/2) Eran Tromer Slides credit: Avishai Wool, Tel Aviv University 1 Administration Lecturer: Eran

More information

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6) Semantic Analysis Scoping (Readings 7.1,7.4,7.6) Static Dynamic Parameter passing methods (7.5) Building symbol tables (7.6) How to use them to find multiply-declared and undeclared variables Type checking

More information

Unit 1. 5. Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Unit 1. 5. Write iterative and recursive C functions to find the greatest common divisor of two integers. [6] Unit 1 1. Write the following statements in C : [4] Print the address of a float variable P. Declare and initialize an array to four characters a,b,c,d. 2. Declare a pointer to a function f which accepts

More information

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C 1 An essential part of any embedded system design Programming 2 Programming in Assembly or HLL Processor and memory-sensitive

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

The Advantages of Dan Grossman CSE303 Spring 2005, Lecture 25

The Advantages of Dan Grossman CSE303 Spring 2005, Lecture 25 CSE 303: Concepts and Tools for Software Development Dan Grossman Spring 2005 Lecture 25 Memory-Management Idioms Dan Grossman CSE303 Spring 2005, Lecture 25 1 No tools or rule today Review: Java and C

More information

X86-64 Architecture Guide

X86-64 Architecture Guide X86-64 Architecture Guide For the code-generation project, we shall expose you to a simplified version of the x86-64 platform. Example Consider the following Decaf program: class Program { int foo(int

More information

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009 Software Engineering Concepts: Testing Simple Class Example continued Pointers & Dynamic Allocation CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009 Glenn G. Chappell Department

More information

A C Test: The 0x10 Best Questions for Would-be Embedded Programmers

A C Test: The 0x10 Best Questions for Would-be Embedded Programmers A C Test: The 0x10 Best Questions for Would-be Embedded Programmers Nigel Jones Pencils up, everyone. Here s a test to identify potential embedded programmers or embedded programmers with potential An

More information

Adding Alignment Support to the C++ Programming Language / Wording

Adding Alignment Support to the C++ Programming Language / Wording Doc No: SC22/WG21/N2341 J16/07-0201 of project JTC1.22.32 Date: 2007-07-18 Phone: +358 40 507 8729 (mobile) +1-503-712-8433 Reply to: Attila (Farkas) Fehér Clark Nelson Email: attila f feher at ericsson

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Tutorial on C Language Programming

Tutorial on C Language Programming Tutorial on C Language Programming Teodor Rus rus@cs.uiowa.edu The University of Iowa, Department of Computer Science Introduction to System Software p.1/64 Tutorial on C programming C program structure:

More information

Objective-C Tutorial

Objective-C Tutorial Objective-C Tutorial OBJECTIVE-C TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Objective-c tutorial Objective-C is a general-purpose, object-oriented programming

More information

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

More information

Programming languages C

Programming languages C INTERNATIONAL STANDARD ISO/IEC 9899:1999 TECHNICAL CORRIGENDUM 2 Published 2004-11-15 INTERNATIONAL ORGANIZATION FOR STANDARDIZATION МЕЖДУНАРОДНАЯ ОРГАНИЗАЦИЯ ПО СТАНДАРТИЗАЦИИ ORGANISATION INTERNATIONALE

More information

Bonus ChapteR. Objective-C

Bonus ChapteR. Objective-C Bonus ChapteR Objective-C If you want to develop native ios applications, you must learn Objective-C. For many, this is an intimidating task with a steep learning curve. Objective-C mixes a wide range

More information

Habanero Extreme Scale Software Research Project

Habanero Extreme Scale Software Research Project Habanero Extreme Scale Software Research Project Comp215: Java Method Dispatch Zoran Budimlić (Rice University) Always remember that you are absolutely unique. Just like everyone else. - Margaret Mead

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

What is COM/DCOM. Distributed Object Systems 4 COM/DCOM. COM vs Corba 1. COM vs. Corba 2. Multiple inheritance vs multiple interfaces

What is COM/DCOM. Distributed Object Systems 4 COM/DCOM. COM vs Corba 1. COM vs. Corba 2. Multiple inheritance vs multiple interfaces Distributed Object Systems 4 COM/DCOM Piet van Oostrum Sept 18, 2008 What is COM/DCOM Component Object Model Components (distributed objects) à la Microsoft Mainly on Windows platforms Is used in large

More information

ECE 0142 Computer Organization. Lecture 3 Floating Point Representations

ECE 0142 Computer Organization. Lecture 3 Floating Point Representations ECE 0142 Computer Organization Lecture 3 Floating Point Representations 1 Floating-point arithmetic We often incur floating-point programming. Floating point greatly simplifies working with large (e.g.,

More information

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2). CHAPTER 5 The Tree Data Model There are many situations in which information has a hierarchical or nested structure like that found in family trees or organization charts. The abstraction that models hierarchical

More information

Operating System Manual. Realtime Communication System for netx. Kernel API Function Reference. www.hilscher.com.

Operating System Manual. Realtime Communication System for netx. Kernel API Function Reference. www.hilscher.com. Operating System Manual Realtime Communication System for netx Kernel API Function Reference Language: English www.hilscher.com rcx - Kernel API Function Reference 2 Copyright Information Copyright 2005-2007

More information

Virtual Servers. Virtual machines. Virtualization. Design of IBM s VM. Virtual machine systems can give everyone the OS (and hardware) that they want.

Virtual Servers. Virtual machines. Virtualization. Design of IBM s VM. Virtual machine systems can give everyone the OS (and hardware) that they want. Virtual machines Virtual machine systems can give everyone the OS (and hardware) that they want. IBM s VM provided an exact copy of the hardware to the user. Virtual Servers Virtual machines are very widespread.

More information

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)

More information

Module 816. File Management in C. M. Campbell 1993 Deakin University

Module 816. File Management in C. M. Campbell 1993 Deakin University M. Campbell 1993 Deakin University Aim Learning objectives Content After working through this module you should be able to create C programs that create an use both text and binary files. After working

More information

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00 MPLAB TM C30 Managed PSV Pointers Beta support included with MPLAB C30 V3.00 Contents 1 Overview 2 1.1 Why Beta?.............................. 2 1.2 Other Sources of Reference..................... 2 2

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

Data Structures using OOP C++ Lecture 1

Data Structures using OOP C++ Lecture 1 References: 1. E Balagurusamy, Object Oriented Programming with C++, 4 th edition, McGraw-Hill 2008. 2. Robert Lafore, Object-Oriented Programming in C++, 4 th edition, 2002, SAMS publishing. 3. Robert

More information

How To Write Portable Programs In C

How To Write Portable Programs In C Writing Portable Programs COS 217 1 Goals of Today s Class Writing portable programs in C Sources of heterogeneity Data types, evaluation order, byte order, char set, Reading period and final exam Important

More information

/* File: blkcopy.c. size_t n

/* File: blkcopy.c. size_t n 13.1. BLOCK INPUT/OUTPUT 505 /* File: blkcopy.c The program uses block I/O to copy a file. */ #include main() { signed char buf[100] const void *ptr = (void *) buf FILE *input, *output size_t

More information

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17 CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17 System Calls for Processes Ref: Process: Chapter 5 of [HGS]. A program in execution. Several processes are executed concurrently by the

More information

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms. COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms 1 Activation Records activation declaration location Recall that an activation

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 20: Stack Frames 7 March 08 CS 412/413 Spring 2008 Introduction to Compilers 1 Where We Are Source code if (b == 0) a = b; Low-level IR code

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

7.1 Our Current Model

7.1 Our Current Model Chapter 7 The Stack In this chapter we examine what is arguably the most important abstract data type in computer science, the stack. We will see that the stack ADT and its implementation are very simple.

More information

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security & BSc. (Hons.) Software Engineering Cohort: BIS/05/FT BCNS/05/FT BSE/05/FT Examinations for 2005-2006 / Semester

More information

Static Code Analysis Procedures in the Development Cycle

Static Code Analysis Procedures in the Development Cycle Static Code Analysis Procedures in the Development Cycle Tools, Technology, and Process in Engineering at Microsoft Mooly Beeri Microsoft Haifa R&D Center Agenda Static code analysis tools PREfix and PREfast

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Today. Binary addition Representing negative numbers. Andrew H. Fagg: Embedded Real- Time Systems: Binary Arithmetic

Today. Binary addition Representing negative numbers. Andrew H. Fagg: Embedded Real- Time Systems: Binary Arithmetic Today Binary addition Representing negative numbers 2 Binary Addition Consider the following binary numbers: 0 0 1 0 0 1 1 0 0 0 1 0 1 0 1 1 How do we add these numbers? 3 Binary Addition 0 0 1 0 0 1 1

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Applying Clang Static Analyzer to Linux Kernel

Applying Clang Static Analyzer to Linux Kernel Applying Clang Static Analyzer to Linux Kernel 2012/6/7 FUJITSU COMPUTER TECHNOLOGIES LIMITED Hiroo MATSUMOTO 管 理 番 号 1154ka1 Copyright 2012 FUJITSU COMPUTER TECHNOLOGIES LIMITED Abstract Now there are

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

Common Data Structures

Common Data Structures Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

More information

ONE OF THE MOST JARRING DIFFERENCES BETWEEN A MANAGED language like PHP,

ONE OF THE MOST JARRING DIFFERENCES BETWEEN A MANAGED language like PHP, 3 Memory Management ONE OF THE MOST JARRING DIFFERENCES BETWEEN A MANAGED language like PHP, and an unmanaged language like C is control over memory pointers. Memory In PHP, populating a string variable

More information

picojava TM : A Hardware Implementation of the Java Virtual Machine

picojava TM : A Hardware Implementation of the Java Virtual Machine picojava TM : A Hardware Implementation of the Java Virtual Machine Marc Tremblay and Michael O Connor Sun Microelectronics Slide 1 The Java picojava Synergy Java s origins lie in improving the consumer

More information

Java from a C perspective. Plan

Java from a C perspective. Plan Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions,

More information

Crash Course in Java

Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is

More information

C Programming Tutorial

C Programming Tutorial C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i C O P Y R I G H T & D I S C L A I M E R N O T I C E All the content and graphics on this tutorial

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

Keil C51 Cross Compiler

Keil C51 Cross Compiler Keil C51 Cross Compiler ANSI C Compiler Generates fast compact code for the 8051 and it s derivatives Advantages of C over Assembler Do not need to know the microcontroller instruction set Register allocation

More information

In this Chapter you ll learn:

In this Chapter you ll learn: Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis

More information

C PROGRAMMING FOR MATHEMATICAL COMPUTING

C PROGRAMMING FOR MATHEMATICAL COMPUTING UNIVERSITY OF CALICUT SCHOOL OF DISTANCE EDUCATION BSc MATHEMATICS (2011 Admission Onwards) VI Semester Elective Course C PROGRAMMING FOR MATHEMATICAL COMPUTING QUESTION BANK Multiple Choice Questions

More information

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; } Functions Recursion C++ functions Declare/prototype int myfunction (int ); Define int myfunction (int x){ int y = x*x; return y; Call int a; a = myfunction (7); function call flow types type of function

More information