C programming Lecture 8 – pointers

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Kernighan/Ritchie: Kelley/Pohl:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Pointers and Output Parameters. Pointers A pointer contains the address of another memory cell –i.e., it “points to” another variable cost:1024.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
M-1 University of Washington Computer Programming I Lecture 13 Pointer Parameters © 2000 UW CSE.
Introduction to C Programming CE
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Overview Pointer Variables Pass by Value Pass by Reference (or by Pointer) Arrays.
C Stack Frames / Pointer variables Stack: Local Variables Pass & Return values Frame Ptr linkage (R5) and PC linkage (R7) Pointer Variables: Defining &
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Pointers CSE 2451 Rong Shi.
CP104 Introduction to Programming Modular Programming Lecture 16__ 1 Modular Programming II Functions with single output Functions with multiple outputs.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
Chapter 6: User-Defined Functions
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Review 1 List Data Structure List operations List Implementation Array Linked List.
M-1 University of Washington Computer Programming I Lecture 13 Pointer Parameters © 2000 UW CSE.
Pointers *, &, array similarities, functions, sizeof.
Method Parameters and Overloading Version 1.0. Topics The run-time stack Pass-by-value Pass-by-reference Method overloading Stub and driver methods.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
Week 12 Methods for passing actual parameters to formal parameters.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSC 215 Pointers and Arrays. Pointers C provides two unary operators, & and *, for manipulating data using pointers The operator &, when applied to a.
Lecture 5 Pointers 1. Variable, memory location, address, value
Stack and Heap Memory Stack resident variables include:
Chapter 7: User-Defined Functions II
CSE 220 – C Programming Pointers.
Pointers in C.
Functions Dr. Sajib Datta
Pointers and Pointer-Based Strings
INC 161 , CPE 100 Computer Programming
C Basics.
Lecture 6 C++ Programming
CSI-121 Structured Programming Language Lecture 16 Pointers
Templates.
User-Defined Functions
INC 161 , CPE 100 Computer Programming
Functions Inputs Output
הרצאה 6: כתובות ומצביעים הקצאה דינמית מחרוזות
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
Simulating Reference Parameters in C
Pointers and Pointer-Based Strings
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Data Structures and Algorithms Introduction to Pointers
CS250 Introduction to Computer Science II
Exercise Arrays.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
CMSC 202 Lesson 6 Functions II.
Presentation transcript:

C programming Lecture 8 – pointers Based on slides designed by Shay Artsi, Aythan Avior, Gitit Rockstein and Saher Ismir for the department of Computer Science, Technion, Israel Institute of Technology Translated and updated by Anne Weill-Zrahia נכתב על-ידי טל כהן, נערך ע"י איתן אביאור. © כל הזכויות שמורות לטכניון – מכון טכנולוגי לישראל

Motivation : swap places We want to exchange the contents of variables x and y . We will do this buy defining a new variable temp int x, y, temp; temp = x; x = y; y = temp; 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

מבוא למחשב בשפת .C כל הזכויות שמורות © Let’s assume now that this operation is performed several times in the code and that we wish to define a function for it. void swap(int a, int b) { int temp = a; a = b; b = temp; } … swap(x, y); This will not give the requested effect (why?) 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Parameter passing to a function – by value In C the value of the argument is passed to a function, this is called passing by value. When a variable is passed to the function, a copy of this variable is passed in fact Even if the function changes its copy , this will not affect the varialb in main program void swap(int a, int b) { int temp = a; a = b; b = temp; } int main() int x = 5, y = 7; swap(x,y); a b temp 7 ? 5 5 7 ? ? 5 What can we do ? x y 5 7 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Example 2 : function for fraction addition Motivation : write a function which receives 4 values x1, y1, x2, y2. and returns In fact it will return 2 values a & b so that Problem : the function returns a single value : 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Addresses of variables in main memory : Address of x { double x; int d; char c; ... } Address of d Address of c 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 x y c 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Addresses, pointer, the operator & &a is the address of a in main memory The operator & is applied to memory cells in main memory The operator * is the opposite of &. int * is a declaration of the address of a variable of type int Same for float,char etc. A variable declared as type * is called a pointer 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

מבוא למחשב בשפת .C כל הזכויות שמורות © Examples of pointer Memory 1004 1000 ? p int y; int a = 3; int *p; p = &a; 1000 3 a 996 ? y char c; char *cp1, *cp2 = &c; double *dp, *dq; double x; dp = dq = &x; 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

מבוא למחשב בשפת .C כל הזכויות שמורות © Pointers – cont. It s not permitted to mix kinds of pointers It is permitted to perform a casting (provided one knows what one is doing) Pointers to functions exist in C , but are not in the scope of this course. int *p; double a; p = &a;   p = (int *)&a; 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Pointers and operator * The operator * is the opposite of & and denotes: *p denotes “contents of p” where p is a pointer Memory int y; int a = 3; int *p; p = &a; y = *p; *p = 7; 1004 ? 1000 p 1000 3 7 a 996 ? 3 y 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Examples with pointers int i = 3, j = 5, *p = &i, *q = &j, *r; double x; Expression Equivalence Value p == &i p == (& i) 1 * * & p * (* (& p))) 3 r = & x r = (& x) /* ? */ 7 * * p / * q + 7 ((7 * (*p))) / (*q)) + 7 11 * (r = & j) *= * p (* (r = (& j))) *= (* p) 15 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Passing pointers to functions void swap(int * a, int * b) { int temp = *a; *a = *b; *b = temp; } int main(void) int x = 5, y = 7; swap(&x, &y); ... Memory *נתעלם מכתובת חזרה וכו' על המחסנית 1040 5 ? temp 1036 ? 1004 b 1032 ? 1000 a 1004 5 7 y 1000 7 5 x 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Pointers as parameters void swap(int * a, int * b) { int temp = *a; *a = *b; *b = temp; } int main() int a, b, c = 1, d = 2; int *p = &b; scanf("%d %d", &a, p); ... swap(&a, &c); swap(p, &d); scanf will update a memory location (store there a value which is read from input) therefore it needs a parameter of type pointer Why not &? 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Example :Function to simplify a fraction Data: numerator and denominator Goal : Update both variable so that they represent the simplified fraction : void reduce(int * x, int * y); Parameters are used both for in and out. int a, b; ... reduce(&a, &b) 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Example – simplification of fractions int gcd(int, int); void reduce(int * p_numerator, int * p_denominator) { int  g = gcd(*p_numerator, *p_denominator); if    ( g > 1 ) { *p_numerator /= g; *p_denominator /= g; } 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Example : addition of 2 fractions Data : 4 values representing 2 fractions. Goal: compute a and b such that החתימה של הפונקציה: void add(int * a, int * b, int x1, int y1, int x2, int y2); x1, y1, x2, y2 are passed by value A,b are passed by reference and are exit parameters. \. int n, m, a1, b1; ... add(&n, &m, a1, b1, 5, 10) What will happen if the 2 first parameters are passed by value? 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Implementation int gcd(int, int); void reduce(int *x, int *y); int lcm(int, int); // Least Common Multiplier void add(int *pa, int *pb, int a1, int b1, int a2, int b2) { *pb = lcm(b1, b2); *pa = a1 * (*pb / b1) + a2 * (*pb / b2); reduce(pa, pb); } int lcm(int n, int m) return n / gcd(n,m) * m; Order of arithmetic operations to avoid overflow 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Passing parameters methods By value Simpler syntax Prevents unwanted change of the variable in calling function Entry parameter Single return value By address (or by reference) More efficient in cases where creation of actual parameter is space consuming Parameters are in, out or in-out Parameters can be changed in calling program This latter can be avoided by using const to declare the parameter const int * p 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

מבוא למחשב בשפת .C כל הזכויות שמורות © The NULL pointer 0 (zero) is a valid value for a pointer Therefore to describe a “zero” pointer there is a bit combination which does not represent any address The NULL pointer is defined in stdio.h as 0 Setting a pointer to NULL means that it is empty, or that is does not contain a valid address in memory int *p = NULL; *p = 7; /* what will happen? */ 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

מבוא למחשב בשפת .C כל הזכויות שמורות © Simple sort Goal : sort 2 numbers of type double. Method : write a function called swap_double which will exchange the 2 values if not in right order Algorithm: if (b < a) swap_double(&a, &b); Prototype of the function: sort2(double *x, double *y); 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Sorting 2 numbers void swap_double(double* x, double* y) { double temp = *x; *x = *y; *y = temp; } void sort2(double* a, double* b) if (b < a) { swap_double(a, b); There is a bug in sort2 – can you find it? Attention: this bug will not be discovered in compilation, nor runtime, just give wrong answers This is the worst type of bug – appears when making a demonstration to the boss …. 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Sorting 2 numbers - correction void swap_double(double* x, double* y) { double temp = *x; *x = *y; *y = temp; } void sort2(double* a, double* b) if (*b < *a) { swap_double(a, b); מדוע אין צורך לשנות את הקריאה ל-swap? 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©

Conclusion and question How can we implement a function which sorts 4 numbers, using our sort2? Prototype: Calling sequence Goal (after calling the function): x ≤ y ≤ z ≤ w. sort4(double * a, double * b, double * c, double * d); sort4(&x, &y, &z, &w); 7 הרצאה מבוא למחשב בשפת .C כל הזכויות שמורות ©