POINTER & REFERENCE VARIABLES

Similar documents
Example: Pointer Basics

[0569] p 0318 garbage

PROGRAMMAZIONE I A.A. 2017/2018

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

Fundamental of Programming (C)

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

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

DECLARAING AND INITIALIZING POINTERS

Fundamentals of Programming Session 20

Pointers. Memory. void foo() { }//return

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

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

... Lecture 12. Pointers

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

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

Programming Language B

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

Pointers. 10/5/07 Pointers 1

Computer Programming Unit 3

Variation of Pointers

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Chapter 11: Pointers

Laboratory 10 POINTERS I. FUNDAMENTALS

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

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

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

EM108 Software Development for Engineers

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Introduction to Scientific Computing and Problem Solving

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

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

CS 61c: Great Ideas in Computer Architecture

Programming in C++ 6. Floating point data types

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

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

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

ECE 15B COMPUTER ORGANIZATION

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Principles of C and Memory Management

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Array Initialization

Homework #3 CS2255 Fall 2012

Pointers, Dynamic Data, and Reference Types

C Programming Language

Today s class. Review of more C Operating system overview. Informationsteknologi

Character Strings. String-copy Example

Pointers. Pointers. Pointers (cont) CS 217

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

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Computer Systems Principles. C Pointers

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

20 Dynamic allocation of memory: malloc and calloc

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

Lesson 7. Reading and Writing a.k.a. Input and Output

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

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

Tutorial 10 Pointers in C. Shuyue Hu

Lecture 04 Introduction to pointers

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Arrays, Pointers and Memory Management

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

Chapter 11: Pointers

UNIVERSITY OF LIMERICK OLLSCOIL LUIMNIGH COLLEGE OF INFORMATICS & ELECTRONICS DEPARTMENT OF ELECTRONIC & COMPUTER ENGINEERING

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

C++ for Java Programmers

Pointers, Arrays, and Strings. CS449 Spring 2016

Arrays and Pointers. CSE 2031 Fall November 11, 2013

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.

Arrays and Pointers (part 2) Be extra careful with pointers!

C Programming Language

CSC 211 Intermediate Programming. Arrays & Pointers

CS201- Introduction to Programming Current Quizzes

Lecture 2: C Programm

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

Pointers. Pointer References

Fundamentals of Programming. Lecture 14 Hamed Rasifard

Arrays and Pointers. Lecture Plan.

MA 511: Computer Programming Lecture 3: Partha Sarathi Mandal

Basic and Practice in Programming Lab7

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Assist. Prof. Dr. Caner ÖZCAN

QUIZ on Ch.8. What is kit?

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

Operators & Expressions

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

Programming in C - Part 2

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

CS 241 Data Organization Pointers and Arrays

Algorithms & Data Structures

MTH 307/417/515 Final Exam Solutions

More about BOOLEAN issues

COMP 2355 Introduction to Systems Programming

Transcription:

Lecture 9 POINTER & REFERENCE VARIABLES Declaring data pointer variables Assignment operations with pointers Referring objects using pointer variables Generic pointers Operations with pointer variables Arrays and pointers Reference variables (only in C++)

Pointers A pointer is a variable that holds a memory address. In terms of content memory area addressed by the pointer variables, distinguish two categories: pointers to data contain the addresses of variables or constant values; pointers to functions contain addresses of executable code (functions).

Declaring pointers of data A data pointer declaration takes the following form: type * variable_name; where: type may be any type of data (fundamental, derived or defined by the user); variable_ name is an identifier. ( * ) is the indirection (or dereference) operator, and it indicates that variable_name is a pointer.

Declaring pointers of data Examples of pointer declaration int * ptr1; char * ptr2; float * ptr3; double * ptr4; int ** ptr5; void * ptr; float * p_r = 0; // pointer to int // pointer to char // pointer to float // pointer to double // pointer to an int pointer (double indirection) // generic pointer - may address any type of data // declaration with initialization

Pointers int var1= 7; int * ptr1 ; ptr1 = &var1; *ptr1 dereferences ptr1 to get to what it points to, and is equivalent to var1; this expression returns the contents of the location to which ptr1 indicates.

Pointers #include <stdio.h> void main() { int iv=10,*iptr; printf("\nthe address of variable iv: %p\n", &iv); printf("\nvalue of iv= %d\n", iv); iptr=&iv; printf("\nvalue of iptr: %p\n", iptr); printf("\niptr address the object: %d\n", *iptr); *iptr=20; printf("\nnow iv has the value %d\n", iv); }

Assignment operation with pointers Assignment operation pointers may take addresses of objects (variables or constants) that are already allocated in memory or addresses derived from the operations of dynamic memory allocation or the constant NULL (0). assignment may be made only if the type of pointer and the type of data which address takes are identical.

Assignment operation with pointers int var1; int *p1; p1 = &var1; double var2; double *p2; p2 = &var2; p2 = &var1; p1 = 0; // error, is assigned an address of a pointer of type // int to a pointer of double // correct - 0 does not refer to any memory address p1 = NULL; p1 = 0xFF00; int *p1, *p2; float *p3; p1 = p2 ; p3 = p2 ; // correct NULL is a constant with 0 value // error, not permitted to assign only the constant 0 or // an address of an object // correct - pointers are the same type // error - pointers are of different types

Assignment operation with pointers For assignement is important that the pointer variable type and type of data from the address taken to be identical, otherwise obtain an error message. Constant 0 (NULL) may be assigned to any pointer variable. Uninitialized pointer variables, similarly to any variable, take value 0 if they a global or static declared, and residual values for automatic variables. It is important that any pointer variable is initialized with a valid value, 0 or address of an object allocated in memory, before being used. Misuse of pointers may cause uncontrolled effects on the program development.

Referring objects by pointers It considers the sequence: tip object_name; tip* pointer_name; pointer_name = & object_name; Syntax to referring the object by the pointer: *nume_pointer Operation is named indirection or pointing Expression *nume_pointer can be used both as rvalue and the lvalue.

Referring objects by pointers Example int var1=7, var2; int * ptr1 = &var1; var2 = *ptr1; *ptr1 = 10;

Generic Pointers You can define pointers to type void. They may take as value addresses of any data type and are called generic pointers. int vi=10; double vr = 1.5; void * pv; pv = NULL; pv = &vi; pv = &vr; // correct // correct // correct For generic pointers indirection it is necessary to specify how to interpret this using explicit conversion. printf( %d, *(int*)pv); // void*pointer is converted at int* printf( %lf, *(double*)pv); // void*pointer is converted at // double*

Operations with pointers Assignment int vi=10; int * pi = 0; pi = &vi; Operators address (&) and sizeof π sizeof(pi); Relational operations (> (greater), >= (greater or equal), < (less), <= (less or equal), == (equal),!= (diffrent)). int*p1, *p2; if(p1<p2) printf( p1<p2 ); if(p1==0) printf( p1 is 0 so it not address any object );

Operations with pointers Arithmetical operations ( + (addition), - (subtraction), ++ (incrementation), -- (decrementation)) int var1, var2, *ptr; ptr = &var1; ptr = ptr +1; Expression (ptr + 1) is a movement in memory with one int (a number of bytes equal to sizeof (int)) float *pf; pf +4; pf++; pf--; // movement with sizeof(float)*4 (16 bytes) // pf increases with 4 bytes // pf decreases with 4 bytes

Arrays and pointers int vector[6]; The name of an array is a memory address (a constant pointer ).

Arrays and pointers int vector[6]; vector - equivalent to - &vector[0] vector + 1 - equivalent to - &vector[1] vector + 2 - equivalent to - &vector[2]... Or: *vector - equivalent to - vector[0] *(vector + 1) - equivalent to - vector[1] *(vector + 2) - equivalent to - vector[2]... or: *vector - equivalent to - vector[0] *vector + 1 - equivalent to - vector[0] + 1 *vector + 2 - equivalent to - vector[0] + 2

Arrays and pointers float tab[20], *ptr; ptr = tab; tab= ptr; // correct // error, tab is a constant &tab[0] = = tab ; &tab[2] = = tab+2 ; tab[0] = = *tab ; tab[2] = = *(tab+2) ; tab++ ; ptr++ ; // true // true // true // error, tab is a constant // correct

Arrays and pointers char *str = STRING ; The elements of the character string can be referred using the pointer str. Expression *str is the first element of the string, ie the character S. Expression *(str+1) is the second element of the string, ie the character T.

Arrays and pointers Example of copying strings void CopyString (char *dest, char *src) { while (*dest++ = *src++) ; }

Arrays and pointers Multi-dimensional arrays are arrays with elements array, so that the name of the array (without index) is a pointer arrays, (pointer to a pointer). float m[10][10]; float *p; p = m; p=(float*)m; // m is a pointer to pointer of 10 float // p is a float pointer // error, different types // correct, is used an explicit type conversion

Arrays and pointers int matrix[3][4] = { { 10, 20, 30, 40 }, { 50, 60, 70, 80 }, { 90, 100, 110, 120 } }; - matrix is a pointer, is a memory address of 4 int array - matrix[0], matrix[1], matrix[2] are pointers of int

Arrays and pointers int mat[3][4]= {1,2,3,4,5,6,7,8,9,10,11,12}; int i, j; printf("\nmemory address: %u, %u, %u", mat, mat[0], &mat[0][0]); printf("\nmemory address: %u, %u, %u", mat+1, mat[1], &mat[1][0]); printf("\nuse indexes :"); printf("\n %u, %u, %d", mat, mat[0], mat[0][0]); printf("\n %u, %u, %d", mat+1, mat[1], mat[1][0]); printf("\nuse pointers:"); printf("\n %u, %u, %d", mat, *mat, **mat); printf("\n %u, %u, %d", mat+1, *(mat+1), **(mat+1));

Arrays and pointers for(i=0 ; i<3 ; i++) { printf("\n"); for(j = 0 ; j<4 ; j++) printf("%4d", mat[ i ][ j ]); } for(i=0 ; i<3 ; i++) { printf("\n"); for(j = 0 ; j<4 ; j++) printf("%4d", *( *( mat+i ) + j)); }

Reference variables (only in C++) A reference (&) is an alias for an object A reference is like a constant pointer that is automatically dereferenced For example, int x; int & r = x; x = 15; both x and r will denote the value 15.

Reference variables (only in C++) A reference must be initialized when it is created. (Pointers can be initialized at any time.) Once a reference is initialized to an object, it cannot be changed to refer to another object. (Pointers can be pointed to another object at any time.) You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.

Reference variables (only in C++) Independent references are rarely used. Instead, use of references as formal parameters allows simple and efficient transfer of data between functions.