1 CS 201 Pointers (2) Debzani Deb. 2 Overview Pointers Functions: pass by reference Quiz 2 : Review Q & A.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 6 Modular Programming J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Chapter 7: User-Defined Functions II
BBS514 Structured Programming (Yapısal Programlama)1 Pointers.
Kernighan/Ritchie: Kelley/Pohl:
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Function with Output Parameters 4 We have seen that functions can return a single value or no value (void return type) 4 It is quite often useful to be.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
TDBA66, VT-03, Lecture - Ch6_21 Function calls A function call implies –Every expression in the argument list is evaluated –If necessary, the value of.
CS 201 Functions Debzani Deb.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Chapter 7 Simple Data Types and Function Calls Alkar / Demirer.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CP104 Introduction to Programming Modular Programming Lecture 16__ 1 Modular Programming II Functions with single output Functions with multiple outputs.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Modular Programming Advantages of using functions (to make a modular program) are: Changing the program into separate pieces Code reusing Easier modification.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Chapter 5 Modular Design and Function C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
1 ICS103 Programming in C Lecture 8: Functions I.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
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.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Problem Solving and Program Design in C Chap. 6 Pointers and Modular Programming Chow-Sing Lin.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter 7: User-Defined Functions II
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng.
ICS103 Programming in C Lecture 3: Introduction to C (2)
Hassan Khosravi / Geoffrey Tien
User-Defined Functions
Chapter 2 - Introduction to C Programming
Simple Data Types and Function Calls
Chapter 2 - Introduction to C Programming
Programming in C Pointer Basics.
Programming in C Pointer Basics.
Assist.Prof.Dr. Nükhet ÖZBEK Ege University
Your questions from last session
DATA TYPES There are four basic data types associated with variables:
Chapter 6 Modular Programming chap6.
FUNCTION ||.
ICS103: Programming in C 6: Pointers and Modular Programming
Presentation transcript:

1 CS 201 Pointers (2) Debzani Deb

2 Overview Pointers Functions: pass by reference Quiz 2 : Review Q & A

3 Uses of & and * p = &x; // p points at x now. y = * p; // y has the value pointed out by the pointer p. * p= 13; // 13 was inserted to the // place pointed out by p. x int p int * y int x int p int *

4 Cont. x int p int * x&xp*p&p 35 & when applied to a variable, yields its address (pointer to the variable). * when applied to an address (pointer), fetches the value stored at that address

5 Arithmetic and Logical Operations on Pointers. A pointer may be incremented or decremented. An integer may be added to or subtracted from a pointer. Pointer variables can be used in comparison, but usually only in a comparison to NULL.

6 Arithmetic Operations on Pointers When an integer is added to a pointer, the new pointer value is changed by the integer times the number of bytes in the data variable the pointer is pointing to. Example p = &x; // size of int is 4 bytes p = p + 2; // address is increased by 8 (2*4) bytes. x int p int * ? ? ? p int *

7 What is the use of Pointers? Pointers can be used to operate on variable- length arrays. Pointers can be used for advanced data structures. Pointers can be “cheaper” to pass around a program. You could program without using them, but you would be making life more easier by using them.

8 The true horror of pointer Each pointer Always points something. No bounds checking – pointers can point outside the array, even outside the program. No type checking – you can cast a pointer to anything. Memory Leaks – you can forget to deallocate storage when you’re done with it. Dangling references – You can deallocate storage before you’re doe with it. You just have to be careful while using pointers.

9 Conclusions Pointers allow more sophisticated programming. But if you mess up with pointers, the things will be real messed up. It is best to only use pointers once you are confident with simpler programming techniques. Pointers bugs are the hardest to find – you might find your program crashes randomly at different points in the code. This is typical of pointer bugs.

10 Functions: Pass by reference

11 Functions In Chapter 3 We looked at 4 types of functions  No arguments, no return value –void printData (void);  One or more arguments, no return value –void drawCircle (int radius);  One or more arguments, one return value –double square (double num); What if we need to return more than one value from a function?

12 Functions: Arguments are passed by values Argument lists are used to communicate information from the main function to its function subprograms.  Arguments make functions more versatile because they allow us to execute the same function with different sets of data. Return values are used to communicate information from the function subprogram back to the main program. We can use output parameters to return multiple results from a function. When a function is called, it is given a copy of the values that are passed in as arguments.  If you manipulate the value of an argument, it has no impact on its value in the main function  Therefore, these are called input parameters, because they can only bring information into the function, and not back out.

13 Example with pass by value void myFunc(int arg); int main(void) { int x = 5; myFunc(x); printf(“%d\n”, x); } void myFunc(int arg) { arg = 4; } /* Output */ 5

14 In main: int x = 5; In main, x is assigned the value 5. This places the value 5 in the memory cell reserved for x In this case, it is at address 0x234

15 In main: myFunc(x); We call the function myFunc and pass it the value of x myFunc allocates a new memory cell for its formal parameter arg The value 5 (a copy of the value in x) is placed in arg

16 In myFunc: arg = 4; In myFunc, arg is assigned the value of 4 This places the value 4 in the memory cell for arg This is not the same cell as x

17 In main: printf(“%d\n”, x); Back in main, when we print out x, the value it points to is still 5.

18 Functions: Arguments are passed by Reference What if we want our changes to the value in the function to affect the value in the main function? We can accomplish that by passing the address of a variable as argument to a function and manipulate that variable inside the function. In the formal parameter list, we put a * in front of the parameter name.  This defines a pointer, which means that we will be passing the address of the value, rather than the value itself. In the function call, we put an & in front of the argument name.  The & tells the compiler to pass the address of the variable, not its value. When we need to access the value of the argument in the function, we put a * in front of the variable name  This * tells the compiler to access the value pointed to by the address in the variable.

19 Example with pass by reference void myFunc(int* arg); int main(void) { int x = 5; myFunc(&x); printf(“%d\n”, x); } void myFunc(int* arg) { *arg = 4; } /* Output */ 4

20 In main: int x = 5; In main, x is assigned the value 5, just like before. The address of the memory cell for x is 0x234 The value of &x is 0x234

21 In main: myFunc(&x); When we call myFunc, we pass it &x, the address of x This value is stored in the memory cell for arg. arg == 0x234, *arg == 5

22 In myFunc: *arg = 4; When we set the value of *arg, we are setting the value pointed to by arg – the value at 0x234

23 In main: printf(“%d\n”, x); Back in main, the value of x is now 4

24 #include void separate(double num, char *signp, int *wholep, double *fracp); int main(void) { double value, fr; char sn; int whl; printf("Enter a value to analyze> "); scanf("%lf", &value); separate(value, &sn, &whl, &fr); printf("Parts of %.4f\n sign: %c\n", value, sn); printf(" whole number magnitude: %d\n", whl); printf(" fractional part: %.4f\n", fr); return 0; }

25 void separate(double num, char *signp, int *wholep, double *fracp) { double magnitude; if (num < 0) *signp = ’-’; else if (num == 0) *signp = ’ ’; else *signp = ’+’; magnitude = fabs(num); *wholep = floor(magnitude); *fracp = magnitude - *wholep; } Parts of sign: + whole number magnitude: 35 fractional part:

26 Figure 6.4 Parameter Correspondence for separate(value, &sn, &whl, &fr);

27 Scope of Names The scope of a name refers to the region of a program where a particular meaning of a name is visible or can be referenced. #define variables scope begins at their definition and ends at the end of the source file. All functions can “see” these variables. The scope of the name of a function begins with the function prototype and ends with the end of the source file. All formal parameter names and local variables are visible only from their declarations to the closing brace of the function in which they are declared. Look at Fig 6.8 and pay particular attention to Table 6.4 until you agree with ALL the visibilities.

28 Quiz 2: Review

29 Quiz 2 Grade Distribution

30 Quiz 2: Tricky Questions The following decision structure is invalid: if x <= y printf("%1f", x); else printf("%1f", y); True: gives you syntax error because the condition is not enclosed in braces. Correct use: if (x<=y)

31 Quiz 2: Tricky Questions The statements on the left always give p the same value as the code on the right, but the code on the right may execute faster. if (x > 15) p = p * x; if (x > 30) else if (x > 30) p = 2 * p * x; False: Different values are assigned to p when x>30. when p = 2 and x = 20 p is 40, 1 st rule triggered when p = 2 and x = 40 p is 6400, both rule triggered p is 80, 1 st rule triggered

32 Quiz 2: Tricky Questions n || a <= b && c != 100 The complement is !(n || a <= b && c != 100) = !n && !((a <= b) && (c != 100)) = !n && (!(a <= b) || !(c != 100)) = !n && ((a > b) || (c == 100))

33 Questions asked during lecture

34 Questions about Pointer int x; int *px; int **py; px = &x; py = &px; *px = 5; printf("X is %d\n",x); printf("*px is %d\n", *px); printf("px is %p\n",px); printf("&x is %p\n",&x); printf("*(&x) is %d\n",*(&x)); printf("&px is %p\n",&px); printf("*py is %p\n", *py); 50xbff7f8a40xbff7f89c py px x 5 0xbff7f8a4 5 0xbff7f89c 0xbff7f8a4 What is *py?

35 Why do you want us to use fabs in lab4? Because of the way double variables are stored (we will see more about this in chapter 7), not all numbers can be represented exactly. Therefore, an equality comparison of two type double values can lead to surprising results. What if the input is ( , 0.0) as (x, y) coordinate value to your program?  There can be a various representation of the number depending on hardware, OS or even compiler. E.g , etc.  You want your code to act consistently irrespective of the environment it is executing on.

36 Example of Challenging Questions 1.What will happen in the following cases. Explain very briefly (one or two lines) printf(“%d %d\n”, 1, 2, 3); printf(“%d %d %d \n”, 1, 2 ); 2.We have seen that all pointer variables (i.e. int *, double *) are of same size (in our case all of them occupy 4 bytes of memory and contain plain and simple addresses). Considering this, can we live without declaring the type of a pointer variable? If your answer is ‘yes’, then explain why? If your answer is ‘no’ then give at least one example showing the absolute necessity of the declaration of pointer variable.