Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Similar documents
[0569] p 0318 garbage

Variables and Operators 2/20/01 Lecture #

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

Goals of this Lecture

Language comparison. C has pointers. Java has references. C++ has pointers and references

A Fast Review of C Essentials Part II

Variation of Pointers

Pointers. 10/5/07 Pointers 1

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

Unit 7. Functions. Need of User Defined Functions

CSE 230 Intermediate Programming in C and C++ Functions

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

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

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

PROGRAMMAZIONE I A.A. 2017/2018

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Procedural programming with C

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Lectures 5-6: Introduction to C

Storage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables.

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Operators And Expressions

First of all, it is a variable, just like other variables you studied

M.EC201 Programming language

Review of the C Programming Language for Principles of Operating Systems

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Storage class and Scope:

Fundamentals of Programming Session 12

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

by Pearson Education, Inc. All Rights Reserved.

A Fast Review of C Essentials Part I

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Lab 3. Pointers Programming Lab (Using C) XU Silei

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

C: How to Program. Week /Mar/05

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Fundamental of Programming (C)

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Computers Programming Course 5. Iulian Năstac

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Functions. (transfer of parameters, returned values, recursion, function pointers).

Chapter 2 - Introduction to C Programming

Programming for Engineers Iteration

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

EL6483: Brief Overview of C Programming Language

Functions and Recursion

15 FUNCTIONS IN C 15.1 INTRODUCTION

Function Call Stack and Activation Records

Functions. Chapter 5


Review of the C Programming Language

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Lecture 3: C Programm

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Fixed-Point Math and Other Optimizations

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

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

Ch. 3: The C in C++ - Continued -

Model Viva Questions for Programming in C lab

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

CS 61c: Great Ideas in Computer Architecture

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

Basics of Programming

Arrays and Pointers. Lecture Plan.

UNIT III (PART-II) & UNIT IV(PART-I)

Programming in C - Part 2

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

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.

Arrays and Pointers (part 1)

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

MYcsvtu Notes LECTURE 34. POINTERS

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Arrays and Pointers in C. Alan L. Cox

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

Lecture 2: C Programm

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

At the end of this module, the student should be able to:

Arrays, Pointers and Memory Management

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Introduction to Scientific Computing and Problem Solving

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

CSCI 171 Chapter Outlines

CS240: Programming in C

Dynamic memory allocation (malloc)

Problem Solving and 'C' Programming

Arrays and Pointers (part 1)

Lecture 04 Introduction to pointers

SYSC 2006 C Winter 2012

Arrays and Pointers in C & C++

CS Programming In C

Transcription:

Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such as binary trees and linked lists. 1 2 What Are Pointers? A pointer is the memory address of an object. A pointer variable is a variable that is specifically declared to hold a pointer to an object of its specified type. This address is the location of another object (typically another variable) in Memory address 1000 1001 1002 1003 1004 1005 POINTERVariable Contents 1003 3 4 memory.... Pointer Declaration Two Pointer Operators General syntax: type *name; int *m; //The variable m can hold a //pointer to type int. char *ch; Address Operator: Dereference Operator: * Both & and * have a higher precedence than all other arithmetic operators except the unary minus, with which they share equal precedence. int count, *y, q; 5 6 & 1

& Operator The & is a unary operator that returns the memory address of its operand. & the address of m = &count; m receives the address of count. m count * Operator It is a unary operator that returns the value located at the address that follows. q = *m; * at address q receives the value at address m.? 100 7 8 Put the value 10 into a variable called target. #include <stdio.h> int main(void) int target, source=10; int *m; m = &source; target = *m; printf("%d", target); return 0; Pointer Assignments You can use a pointer variable on the right-hand side of an assignment statement to assign its value to another pointer. When both pointers are the same type, the situation is straightforward. 10 #include <stdio.h> int main(void) int x = ; int *, *; = &x; = ; printf("%p %p",, ); printf(''%d %d\n", *, *); return 0; Illustrates Distinction between a pointer var value & a Dereference variable. main( ) int i = 777, *p = &i; printf ( value of i:%d\n, *p); printf ( Addr of i:%u or %p\n, p, p); Output value of i: 777 Addr of i: 23488025 or dfffcfc u - (unsigned Dec integer) p - (whatever way is Default for system) - Here is Hex. 11 12 2

Example 1 int i = 1, *j, *k; Assume addresses of i, j, k are respectively Byte addresses 10, 20, 30 i:10 j:20 k:30 1. j = &i; 1? int var Pointer var Pointer var 1 10? i:10 j:20 k:30? 13 2. *j = 2; 1 2 10? i:10 j:20 k:30 Stores 2 at the memory location pointed to by j. 3. i = *j + 1; 12 3 10? i:10 j:20 k:30 * has higher precedence than +. Assigns to i the contents of the location pointed to by j, incremented by 1. 14 4. k = &i; 3 10 10 i:10 j:20 k:30 5. printf ( %d, *k); int a=42, b=53, *, *; = &a; = ; = &b; Example 2 output: 3 15?? *? *? 16 int a=42, b=53, *, *;?? 42 53 = ; = &a;? 42 53 = &b; 42 53 42 Example 3 int *, v1; v1 = 0; = &v1; * = 42; int a=8, b=; int *, *; v1?? *? = &a; = &b; = ; vs. * = *; 53 17 18 3

= ; before * = *; before 8 8 after after 8 1 Example 4 # include <stdio.h> main( ) int j, i, *intptr; scanf( %d%d, &i, &,j); intptr = i > j? &i:&j; printf( %d\n, *intptr); Address of the larger var is stored in? : then the larger number is output. 20 Example 5 int a=3,b=7,*p; p = &b; 3 7 a b p Pointer Initialization int i, *p = &i; correct *p=2**p a; printf ( b= %d\n, b); int *p = &i, i; sequence wrong. The object pointed to by p (i.e., b) is assigned the value of 2**p a. 1) 2 * *p 2 * 7 2) 14 3 11 3) Which is assigned? b The variable must be defined before the address can be assigned. 21 22 11 p = &i; p = 0; p = NULL; p points to i Null is usually defined as 0. Pointer constant points nowhere. p = (int *) 1307; cast to pointer to int. 1307 is an absolute address in memory. 23 int i = 3, j = 5, *p = &i, *q = &j, *r; double x; 3 5 i:10 j p:50 q? x 1) p = i + 7; ILLEGAL The only integer value that can be assigned to a pointer variable directly is the special value 0 (NULL). To assign any other value requires a cast (int *) (i + 7) r? 24 4

2) **&p All are unary operators. 1 &p - The address of p (50). 3) r = &x; Illegal Why? x is a double variable r is pointer to int. 3 10 i:10 p:50 2 3 *&p - The Addr stored at p (10) **&p The contents of the address (*&p) The contents of the variable pointed 25 to by p i.e., 3 4) 7 * *p / *q + 7 i:10 j 3 5 Dereference Right to Left p q 1. *q 5 2. *p 3 3. 7 * 3 [21] 4. 21/5 4 5. 4 + 7 11 26 5) *(r = &j) *= *p 4 2 1 5 3 j - int var p - pointer to int j i r - pointer to int 5 3 r p 1. &j - Address of j 1 2. r = 1 r points to j 3. *p contents of thing pointed to by p i.e., 3 4. *( ) Location pointed to by r, i.e., j. 5. *= *r *= *p; *r = *r * *p; 27 int *v=(int *)100; assume int are 2 bytes long. Pointer Arithmetic Byte Address. 100 v 102 v + 1 104 v + 2 106 v + 3 108 v + 4 28 char *ch= (char *)3000; Only two operations are allowed. Addition and subtraction. int *i= (int *)3000; ch ch+1 ch+2 ch+3 ch+4 ch+5 3000 3001 3002 3003 3004 3005 I i+1 i+2 e.g. p++; p--; = +12; Cannot multiply or divide pointers. Cannot add two pointers. Cannot add or subtract type float or double to or from pointers. 2 30 5

Call by Reference Passing a ADDRESS of the argument to a formal parameter which is a POINTER of the same type as the argument. Code within the function can change the value of the argument passed to the function. Steps 1) Declare a function parameter to be a pointer. 2) Pass an address as an argument when the function is called. 3) Use the dereferenced pointer in the function body to reference the argument in the calling function. 31 32 #include <stdio.h> void swap(int *x, int *y); int main (void) int i=10, j=20; printf("i and j before swapping: %d %d\n", i, j); swap(&i, &j); /* pass the addresses of i and j */ void swap( int *x, int *y ) int temp; temp=*x; /* save the value at address x */ *x =*y; /* put y into x */ *y=temp; /* put x into y */ printf("i and j after swapping: %d %d\n", i, j); return 0; 33 34 Every variable or function in C has 2 attributes: Storage Classes Type Storage Class Storage Class : determines how the compiler allocates memory to that variable. Auto Extern Register Static 35 36 6

Storage Class of a C object defines its: 1) Spatial Territory- Defines where it can be referred to in the program. Its Scope or Visibility. 2) Temporal Authority- Defines when an object is available. The Extent to which it exists. 37 Auto Variables The storage class auto can only be used in a block: it cannot be used at the global level. 1) Spatial Limitation (scope): The auto variable is limited to the block in which it is defined and its sub-blocks. LOCAL. 2) Temporal Limitation (extent): Are alive only when the block in which they are defined is running. Variable does not exist before block execution, when block terminates it dies(mortal). 38 Impact of Auto Auto is the default SC for local vars because it makes the most efficient use of memory. Good programmers use Auto when ever possible because their lifetime is brief and their scope is limited to one function. They provide an effective way to isolate the actions of each program unit from the others. auto Most common of the four storage classes. Variables declared within function bodies are auto by default. Thus auto is rarely explicitly specified. auto int a,b,c; auto float f; 3 40 Unintentional interference between functions is minimized and, making it much easier to debug large programs. Constant allocation and de-allocation of auto vars does add some overhead to the the execution time, but since is done quite efficiently, the time wasted is minimal and the advantages of the added modularity are great. 41 When a block is entered, the system allocates memory for the auto variables. When Block is exited the variables are released and their values lost. IF re-enter the Block? Memory is re-allocated. 42 7

Call by Reference with Auto Parameters 1) When the block is suspended, such as when it calls another function, a variable can still be accessed and changed(e.g. if it is used as an actual argument in a func call). 2) It can still be referenced and changed through a pointer to it. When the block becomes active again, the variable becomes active i.e., can directly reference it by name.) Extern Primary purpose is to make variables visible to other compilation units. Must be defined in the global area of a program, that is outside of any block. All global variables( i.e., those defined outside any function) are EXTERN by default.!!!!! EXTERN variables are DANGEROUS and should be used with CAUTION!!!!! 43 44 Extern Characteristics Spatial Limitation(global): It is visible from its definition to the end of the program. It can be referred to and changed by all blocks that come after it as well as by other programs that are aware of its existence. Variables declared outside of a function have extern storage class by default. i.e., even if don t use keyword extern. Extern Var s are initialized to 0 automatically. Temporal Limitation(Immortal): The whole life of the program. From the time of its allocation till the end of the program. 45 extern - Look for the variable elsewhere either in this or another file. 46 Register Storage Class Variables so declared should be stored in high speed memory i.e., Registers(cpu) provided if is possible to do so. Defaults to Auto if register not available 47 Typically, the compiler has only a registers available. few such Many are required for system use & can t be allocated otherwise: * Base Addr of program * Return Addr after pgm execution ends, * Instruction reg, program counter, etc.. 48 8

It is an attempt to improve execution speed. Most frequently accessed variable loop control variable or function parameters. register int i ; for (i = d, i <LIMIT, ++i) Recommendation Don t Use The standard states that you can t compute the address of a register. That means you can t use the address operator or indirection operator(*) with a Register variable. If storage class is present & Type is absent - get int. register i ; 4 Secondly, the compiler may ignore your recommendation. 50 Static Storage Class A static variable can be defined inside a block(local) or in the global area of the program. Its characteristics differ slightly depending on where it is defined. We will look at each separately. 51 Local Static Variables Static variable is defined inside a block: 1) Spatial Limitation: LOCAL, undefined outside the block. 2) Temporal Limitation (Extent): Immortal. It lives as if it were a global variable. What are the consequences of the immortal extent? 52 Locally defined Static variables are one of the truly significant features of the C language. 1) Allow a Local variable to retain its previous value when a block is re-entered. (Not the case with Auto) 2) In other languages, these variables must be declared globally, which reduces the benefits of data hiding and isolation. 3) The variable will be automatically initialized to 0 when allocated. ONCE 53 Void f(void) static int cnt = 0; ++ cnt; if (cnt % 2 == 0)...... else..... 1st Time Function Invoked cnt is set to 0. Upon EXIT cnt NOT cleared from memory invocation, retains previous value. 54

Global Static Variables Global variables - that is, variables defined outside the scope of all blocks - can be referred to from other compilation units. To prevent a global variable from being exported to the LINKER for reference by other compilation units, it can be declared static. 55 Global Static Characteristics: 1) Spatial Limitation(scope): Global. Visible from its definition to the end of the compile unit. Guarantees that the scope does not extend beyond its spatial area, i.e., the current complilation unit. 2) Temporal Limitation(extent) Immortal. Same as local static, it lives as global variables live. 56 Static Extern Variable Restricted in scope to the remainder of the file in which they are defined. Not known to other files(compilation units). void f(void) /* v not available here */ static int v; void g(void) /* v can be used here */ A Function can be Static: The scope of the function is limited to one file only(privacy concern). Is known throughout the entire file. void f(int a).. /* g() is available here, but not in other files */ static int g(void).. 57 58 Default Initialization Extern & Static vars are initialized to 0 by the system. Auto & Register are usually not initialized by system. Start will garbage. 5 Type Qualifiers Two type qualifiers: const volatile They are used in declarations and must be coded after the storage class but precede the type names that they qualify. static const int k = 3; Control how variables may be accessed or modified. 60 10

const Variables of type const may not be changed by your program. The compiler is free to place variables of this type into read-only memory (ROM). #include <stdio.h> void sp_to_dash( const char *str); int main(void) sp_to_dash("this is a test"); return 0; const int a=10; const int a=7; int *p=&a; //wrong const int a=7; const int *p=&a; //correct 61 void sp_to_dash(const char *str) char *here = str; while(*here) if(*here = = ' ') printf("%c", '-'); else printf("%c", *here); here++; WHY? 62 Volatile The modifier volatile tells the compiler that a variable's value may be changed in some unspecified way by the hardware. For example, a global variable's address may be passed to the operating system's clock routine and used to hold the system time. Programmers use Volatile objects in advanced systems programming(beyond our scope). Declaration vs. Definition In General, a Declaration is a program element that provides a compiler with essential information or useful advice. When you specify the type of a variable or parameter you are said to declare variable or parameter. 63 64 A definition causes a compiler to set aside memory at compile time (every variable definition is a declaration) - not always the reverse. e.g. when you introduce a variable outside of any function definition (global variable), you both declare and define the variable, because you have: a) informed the compiler about the variable s type. b) caused the compiler to set aside memory When you introduce a variable inside a function definition(local), you only declare that variable, because the compiler does not set aside memory for such variable at compile time [memory in stack frame]. Functions are both declared & defined Because: a) must specify return type. b) compiler sets aside memory for functions at compile time. for the variable at compile time. 65 66 11