Pointer Declarations

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

Introduction to Scientific Computing and Problem Solving

EL2310 Scientific Programming

by Pearson Education, Inc. All Rights Reserved.

Review of the C Programming Language for Principles of Operating Systems

Type Checking. Prof. James L. Frankel Harvard University

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

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

Array. Prepared By - Rifat Shahriyar

Tokens, Expressions and Control Structures

Module 6: Array in C

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CS 376b Computer Vision

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

Goals of this Lecture

Arrays and Pointers. CSE 2031 Fall November 11, 2013

C Programming Review CSC 4320/6320

Review of the C Programming Language

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Programming for Electrical and Computer Engineers. Pointers and Arrays

EL6483: Brief Overview of C Programming Language

Homework #3 CS2255 Fall 2012

Introduction to C++ with content from

Pointers and Arrays 1

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

CSC 211 Intermediate Programming. Arrays & Pointers

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

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

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Arrays and Pointers (part 1)

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

What have we learned about when we learned about function parameters? 1-1

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Chapter 9. Pointers and Dynamic Arrays

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

Short Notes of CS201

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Arrays and Pointers in C. Alan L. Cox

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

INTRODUCTION 1 AND REVIEW

CS201 - Introduction to Programming Glossary By

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

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

C-LANGUAGE CURRICULAM

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

Computer Organization & Systems Exam I Example Questions

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Unit IV & V Previous Papers 1 mark Answers

CS 61c: Great Ideas in Computer Architecture

CMSC 202. Pointers Dynamic Memory Allocation

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Arrays. Arizona State University 1

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Review of Important Topics in CS1600. Functions Arrays C-strings

Exam 3 Chapters 7 & 9

Computer System and programming in C

C Structures & Dynamic Memory Management

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

CS349/SE382 A1 C Programming Tutorial

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

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Arrays and Pointers (part 1)

Dynamic Data Structures. CSCI 112: Programming in C

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

C++ Programming Chapter 7 Pointers

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

Character Strings. String-copy Example

COMPUTER APPLICATION

Lectures 5-6: Introduction to C

Unit 7. Functions. Need of User Defined Functions

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

BLM2031 Structured Programming. Zeyneb KURT

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

A Fast Review of C Essentials Part I

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

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

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

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Extending SystemVerilog Data Types to Nets

Fundamentals of Programming Session 20

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Programming. Pointers, Multi-dimensional Arrays and Memory Management

[0569] p 0318 garbage

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Pointers and Dynamic Arrays

IV Unit Second Part STRUCTURES

How to declare an array in C?

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

UNIT- 3 Introduction to C++

We do not teach programming

Transcription:

199 In C almost all pointers hold the addresses of variables of one specific type. variables. In C a pointer is a special kind of variable whose value if the address of other Address The location of the variable in memory Value The contents of the variable Thus every variable has two attributes. The location of a variable in memory is called the address of the variable. the memory of the computer. During the execution of a program, all variables in the program are stored in Pointers in C 0 Hiroshi Hayashi, 1997 c David B. Wortman, 1995, 1996, 1998,1999 c distribution are expressly prohibited. Copying for purposes other than this use and all forms of University of Toronto students taking CSC181F in the Fall term 1999/2000 at the These lecture notes are provided for the personal use of CSC 181F Lecture Notes Reading Assignment K.N. King Chapter 11, 12 K.N. King Section 17.7 198 Pointer Declarations type-name *pointervar type-name is the base type for the pointer. Use void to specify a generic base type. int * P /* P is a pointer to integer variables */ void * Q /* Q is a pointer with no type */ Use the address-of operator ( & ) to create addresses of any ordinary variable. The pointer dereferencing operator ( * ) is used to access the variable that a pointer variable is pointing at. WARNING: C does NO automatic run-time checking for proper pointer usage WARNING: it is an ERROR to apply the * operator to an uninitialized pointer variable. The + + and - - operators change a pointer variable by size of object that the pointer points at. This feature should only be used to access consecutive elements of arrays. 200

Pointer Example int J, K = 12, * intptr intptr = & K /* Set intptr to address of K */ J = * intptr /* Do J = K the hard way */ * intptr = 17 /* Do K = 17 using intptr */ Variable Value Address J 1 2 0xFFAD1284 K 1 7 0xFFAD1288 intptr 0 x F F A D 1 2 8 8 0xFFAD128C 201 Pointer Variable Values A pointer variable can have one of four values 1. Uninitialized. The variable has never been given a value. 2. NULL. This is a distinguished value that is by convention used to indicate a pointer that doesn t point at any object. For convenience in building loops, NULL usually has the same value as false. 3. Compatible address. The pointer variable points at an object of its declared type 4. Incompatible address. The pointer points at some object (or at some random location in memory) that is not compatible with its declared type. It is an ERROR in C to 1. Apply the pointer dereferencing operator ( * )to an uninitialized pointer. 2. Apply the pointer dereferencing operator ( * )to a pointer that has the value NULL 203 More Pointer Examples int J, K, *P, *Q P = & J? Q = P Q P J *P = 1 P Q 1 J P = & J Q = & K P 1 J J = 1 Q? K * Q = * P P 1 J Q 1 K Note the difference between Q = P and *Q = *P. 202 It is extremely poor programming practice to do anything with a pointer that has an incompatible address. Such usage is non-portable and inherently error prone. Pointer variables of type void * are used to store pointers that do have a declared type. There are NO operations defined for the data type void, so directly dereferencing a void pointer is an ERROR. Any use of a void pointer will require a type cast to make it legal. Example: int J = 23, K, * IP void * VP IP = & J VP = IP K = * VP /* ILLEGAL */ K = ( int ) * VP IP = ( int * ) VP 204

400 I+ + ) for ( XP = & X[ 0 ], YP = & Y[ 0 ] XP Arrays and Pointers In C it ia assumed that if A is an array and J is less than K, the address of A[ J ] is less than the address A[ K ]. int A[1000], sum = 0, * P for ( P = & A[0] P & A[ 1000 ] P++ ) sum + = * P The * and + + operator can be combined in statements that process array elements. int A[ 100 ], * P, J, K, sum P = & A[ K ] The statement * P+ + = J (or * ( P+ + ) = J) assigns J to A[ K ] and sets P to points at A[ K + 1 ]. Example: P = & A[0] while ( P & A[ 100 ]) sum + = * P + + 205 The name of an array is the same as a pointer to the first element of the array. It is a pointer constant. int A[10] * A = 7 /* stores 7 in A[0] */ * (A+3) = 12 /* stores 12 in A[3] */ A++ /* ERROR, can t modify pointer constant */ A pointer to an array can be denoted by enclosing * pointervar in parentheses. int (* P)[10] /* P is a pointer to array of length 10 */ int * Q[20] /* Q is an array of 20 pointers to int */ WARNING: C does not check addesses computed using pointer arithmetic. Good Style: NEVER use pointer arithmetic to address outside of an array. There is an equivalence between array subscripting and pointer dereferencing. A[ K ] is the same as * ( A + K ) or * ( & A[ 0 ] + K ) 207 Pointer Arithmetic and Arrays C supports the following pointer arithmetic Adding/subtracting an integer K to/from a pointer P yields a pointer to the element that is K places after/before the one that P points to. int A[10], * P, * Q, N P = & A[2] Q = P + 3 /* Q points to A[5] */ P += 6 /*P points to A[8] */ Subtracting pointers yields the distance (measured in array element) between the pointers. P = & A[5] Q = & A[1] N = P - Q /* N is 4 */ N = Q - P /* N is -4 */ 206 HOW TO Use Pointers in Array Loops It is often more efficient or more convenient to use a pointer rather than an index to process an array. If the type of the array element is type-name, use a pointer variable with type type-name * For an array A, the address of the first element in the array is & A[ 0 ] If ASIZE is the size of the array, the address of the last element in the array is & A [ ASIZE - 1 ] The address of the first element that is not in the array is & A[ ASIZE ] double X[ 400 ], Y[ 400 ] double X[ 400 ], Y[ 400 ] int K double * XP, * YP...... for ( I = 0 I & X[ 400 ] ) X[ K ] = Y[ K ] * XP+ + = * YP+ + 208

For any one dimensional array type-name A [ ASIZE ] type-name * P is a pointer to array elements & A [ 0 ] is the address of the first element & A[ ASIZE - 1 ] is the address of the last element & A[ ASIZE ] is an address just beyond the end of the array To loop through an entire array, set the pointer to start at the first or last element of the array P = & A[ 0 ] or P = & A[ ASIZE - 1 ] Move through the array using the + + or - - operators Note: that these operators change P in units of one array element The end of loop condition is P & A [ ASIZE ] or P <= A[ ASIZE - 1 ] ( up counting ) P >= & A [ 0 ] (down counting) Loop templates for ( P = & A[ 0 ] P & A [ ASIZE ] P + + )... for ( P = & A[ ASIZE - 1 ] P >= & A[ 0 ] P - - )... 209 Pointers, Parameters and Arguments A function parameter that is declared as a pointer allows the function to directly access variables in the calling program. This mechanism is used for several purposes As an alternative way to specify array parameters. type-name A[] is the same as type-name * A To avoid passing large objects (e.g. structures and unions) by value. To allow a function to return more than one value. To allow a function to process linked data structures like trees and lists. The function parameter is declared as a pointer to the appropriate type. The corresponding argument must be 1. The address of a variable of that type created using the & operator. 2. A pointer to an object of the same type. WARNING: Many C compilers do not check pointer arguments carefully. 211 Multidimensional Arrays and Pointers For any two-dimensional array A, the expression A[ K ] is a pointer to the first element in row K of the array. The name of two-dimensional array is a pointer to pointer. int A[10][10] /* A has type int * * (pointer to pointer to int) */ Examples: int A[NUM ROWS][NUM COLS], *P, K /* Clears row K of the array A */ for ( P = A[ K ] P A[ K ] + NUM COLS P+ + ) * P = 0 int A[NUM ROWS][NUM COLS], K, (*P)[NUM COLS] /* Clears column K of the array A */ for ( P = A P <= & A[ NUM ROWS - 1 ] P+ + ) (* P)[ K ] = 0 210 Pointer Parameter Example int F( int * Z ) /* function prototype */ int X, N, * P P = & X scanf( %d, P) /* Note no & in front of P */ N = F( & X ) /* equivalent to N = F( P ) */ decompose( 3.14159, & K, & F ) void decompose( float X, int *int part, float *frac part ) *int part = (int) X *frac part = X - *int part X 3.14159 int_part 3 K frac_part 0.14159 F 212

Pointer Returning Functions A function may be declared to return a pointer to some type of object. Declare the function as: type-name * functionname( parameters ) the following rules apply to the value of the pointer returned by such a function The pointer should always be a pointer to an object of the correct type. If the pointer isn t null then it should point to a variable outside of the function or to some storage that was newly allocated by the function. WARNING: a pointer pointing to the local (automatic) storage of a function points at GARBAGE after the function returns. It is an ERROR to return a pointer to any of the functions local variables. Those variables cease to exist when the function returns. 213 The function constant assigned to a function pointer should always be compatible with the declaration for the function pointer variable. The function constant passed as an argument to a function pointer parameter should always be compatible with the corresponding parameter declaration. Compatible means The type returned by the function is the same. Corresponding parameters are of the same type. The number of parameters is the same. If these rules are not followed CHAOS will ensue. 215 Pointers to Functions type-name ( * funcpointer )( parameterlist ) This declaration declares a pointer variable ( funcpointer ) that is a pointer to a function. The function returns the type of value specified by type-name and accepts the arguments specified by parameterlist The name of any declared or defined function is a function pointer constant. These are the only values that may be assigned to function pointer variables. This mechanism is typically used for two purposes 1. To allow functions to take a function name as an argument. 2. To create function variables that take on the value of more than one function constant. 214 Function Pointer Examples float bisection( float (*funcptr)( float ), float x0, float x1 ) float function1( float x ) float function2( float x ) y = bisection( function1, 0.0, 2.0 ) y = bisection( function2, -10.0, 10.0 ) float bisection( float (*funcptr)( float ), float x0, float x1) y = ( * funcptr)(x0) 216

mystruct Reading Assignment K.N. King Chapter 16, 18 Supplementary reading S. McConnell Chapter 12 217 Structure Declaration struct structuretag structurefields identifierlist The structuretag provides a name for the structure. This name can be used like a type name to declare variables of the structure type. The optional identifierlist is a list of structure variables that are being declared at the same time as the structure. The structurefields are ordinary data declarations that describe data contained in the structure. Example: struct exstruct typedef struct char name[ 25 ] char label[ 33 ] int price float value computer1, computer2 struct exstruct computer3 mystruct s1, s2 219 220 S4 mya S4 S3 J K S3 int J, K struct S1 S2 struct A S1, S2 /* Variable declarations */ typedef struct A mya struct A * nexta nexta double X, Y char C C Y A X int B, C D struct A B /* Type declarations */ Structure Declaration Examples 218 any structure or union that has a significant use in a program. Good Style: always use a typedef to create a single point of definition for data items need to be stored. A union is a mechanism for saving space when several mutually exclusive student name, student number, assignment marks X coordinate, Y coordinate, Z coordinate Examples: name, address, telephone number informantion needs to be processed in a program. Structures are typically used when some block of logically related be treated as a single entity. A structure is a mechanism that allows several data items of arbitrary types to Structures and Unions

HOW TO Use Structures Each structure body represents a new scope. Declare the variables that you want to treat as a unit in this scope. Structure variables can be initialized with declaration by giving a list of values for the structure fields. struct compstruct char name[ NAME LEN + 1 ] int price computer1 = IBM, 3499, computer2 = Dell, 2265 The assignment operator applies to entire structures. The contents of the structure on the right side of the = is copied to the structure on the left side. computer2 = computer1 Entire structures can not be compared. 221 HOW TO Use Structures The primary use of structures is to package several related variables together so that they can be treated as a single object. Structures can be used as function arguments anda function can return a structure as its value. WARNING: Structures are copied when they are passed by value or returned. Excessive copying of large structures can make a program inefficient. Consider using a pointer to the structure instead. Any type of object can be used as a field of a structure including another structure. Examples: struct A struct B float X, Y struct A BownA int K int K mya Array[ 10 ] typedef struct A mya 223 To access a field in a structure variable, use the field access operator. computer1.price = 2199 If P is a pointer variable that has been declared as a pointer to some structure type S, then (assuming P points at a structure) the fields of the structure can be accessed using the pointer operator -> struct compstruct compptr = & computer2 compptr -> price = 3799 the fields in a structure can be any C type-name including arrays and structures. If a structure has a structure tag, a pointer to the structure can be declared inside the structure. The size of a structure is approximately the sum of the sizes of the fields in the structure. Use sizeof to get the exact size of any structure. 222 Union Types union uniontag fieldalternativeslist identifierlist uniontag is the name of the union type The fieldalternativeslist is a list of mutually exclusive fieldalternatives. Each fieldalternatives is a single data declaration. Use a structure to pack several data items into one alternative. The optional identifierlist is a list of union variables that are being declared at the same time as the union. 224

Union Declaration Examples /* Type declarations */ union A int B, C double X, Y char C struct A * nexta typedef union A myua /* Type declarations */ union typeoverlay int integer float floater unsigned char bytes[ 4 ] void * pointer 225 Example of a self-identifying structure/union. typedef enum utype struct ustruct utype unionkind union point, square, circle, triangle double side /* square */ int radius /* circle */ float sidea, sideb, sidec /* triangle */ value double Xcoordinate, Ycoodinate ukind side radius sidea value sideb Xcoordinate Ycoordinate 227 sidec HOW TO Use Unions Unions are a mechanism for saving space when several mutually exclusive alternative sets of data need to be stored and treated like a single object. The fieldalternatives overlap in memory so only one is active at any instant in time. The size of a union is approximately the size of the largest field alternative in the union. Use sizeof to get the exact size of a union. C does NO run-time checking for proper use of unions The programmer must provide some way of indicating which field alternative is active at any instant in time 226